Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this quick tutorial, we’re going to learn how to find the IP address of a client computer connected to a server.

We’ll create a simple client-server scenario to allow us to explore the java.net APIs available for TCP/IP communication.

2. Background

Java applications use sockets for communicating and sending data over the internet. Java provides the java.net.Socket class for client applications.

The java.net.ServerSocket class is used for TCP/IP-based server-side socket implementation. However, let’s focus only on TCP/IP applications.

3. Sample Use-Case

Let’s assume that we have an application server running on our system. This server sends greetings messages to the clients. In this case, the server uses a TCP socket for communication.

The application server is bound to a specific TCP port. Its socket address is the combination of that port and the IP address of the local network interface. For this reason, the client should use this particular socket address for connecting to the server.

4. Sample Application

Now that we’ve defined our use-case, let’s start by building the server.

4.1. The Application Server

First, we need to instantiate a ServerSocket for listening to incoming connection requests. The constructor of the ServerSocket class requires a port number as an argument:

public class ApplicationServer {

    private ServerSocket serverSocket;
    private Socket connectedSocket;
  
    public void startServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        connectedSocket = serverSocket.accept();
        //...

4.2. Obtaining the Client IP Address

Now that we’ve established our Socket for the incoming client, let’s see how to obtain the client’s IP address. The Socket instance contains the socket address of the remote client. We can use the getRemoteSocketAddress method to inspect this.

ThegetRemoteSocketAddress method returns an object of type SocketAddress. This is an abstract Java class. In this instance, we know it’s a TCP/IP connection, so we can cast it to InetSocketAddress:

InetSocketAddress socketAddress = (InetSocketAddress) connectedSocket.getRemoteSocketAddress();

As we’ve already seen, a socket address is a combination of an IP address and port number. We can use getAddress to get the IP address. This returns an InetAddress object. However, we can also use getHostAddress to get a string representation of the IP address:

String clientIpAddress = socketAddress.getAddress()
    .getHostAddress();

4.3. Sending Greeting Message to the Client

Now, the server and client can exchange greeting messages:

String msg = in.readLine();
System.out.println("Message received from the client :: " + msg);
PrintWriter out = new PrintWriter(connectedSocket.getOutputStream(), true);
out.println("Hello Client !!");

5. Test the Application

Let’s now build a client application to test our code. This client will run on a separate computer and connect to our server.

5.1. Build a Client Application

First, we need to establish a Socket connection to the service using the IP address and the port number:

public class ApplicationClient {
    public void connect(String ip, int port) throws IOException {
        clientSocket = new Socket(ip, port);
    }
}

Similar to the server application, we’ll use the BufferedReader and PrintWriter to read from and write to the socket. For sending messages to the server, let’s create a method to write to the connected socket:

public void sendGreetings(String msg) throws IOException {
    out.println(msg);
    String reply = in.readLine();
    System.out.println("Reply received from the server :: " + reply);
}

5.2. Run the Application

Next, let’s run the client application, choosing a free port for it.

After that, we need to start the client application from another PC. For this example, let’s say the IP address of the server machine is 192.168.0.100 and port 5000 is free:

java -cp com.baeldung.clientaddress.ApplicationClient 192.168.0.100 5000 Hello

Here, we’re assuming that the client and server are on the same network. After the client establishes a successful connection to the server, the IP address of the client will be printed on the server console.

If the client IP address, for example, is 192.168.0.102, we should be able to see it in the console:

IP address of the connected client :: 192.168.0.102

5.3. What Happened in the Background?

In general, when the application server is started, the ServerSocket instantiates a socket object using the given port number and a wildcard IP address. After that, it changes its status to “Listening” for incoming connection requests. Then, when the client sends a connection request, ServerSocket instantiates a new socket by invoking the accept method.

The newly created socket instance contains the IP address and port of the server as well as the remote client. For server IP address, the ServerSocket class uses the IP address of the local network interface through which it received the incoming request. Then, to obtain the remote client IP address, it decodes the IP header of the received TCP packet and uses the source address.

6. Conclusion

In this article, we defined a sample client-server use-case and used Java socket programming to find the IP address of a client connected to a server.

As always, the code of this application is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.