i262666
i262666

Reputation: 23

How to get the client's IP address in Java stream communication

I have a Java server program processing clients requests using socket streams. And it works fine. However, I need to see the client's IP address on the server side. I see several similar questions here and they all recommend using the getRemoteSocketAddress() (or getInetAddrees()) method.

Here is an example:

ServerSocket serverSocket_A = new ServerSocket(port1);
Socket clientSocket_A = serverSocket_A.accept();

The program is blocked here listening for a client's request. When the request is received processing continues. And that means that clientSocket_A is already connected to the remote client.

Now, if I issue

requesterAddress = clientSocket_A.getRemoteSocketAddress().toString();

it returns this strange address: 0:0:0:0:0:0:0:1 instead of 127.0.0.1 (my client is on the local machine).

Any idea how to resolve this issue?

Interesting, that I also have a ClientSocket_B, set inside this server program, that connects to to the Web Server. Applying the same method for this clientSocket_B

Socket clientSocket_B = new Socket(WebServerHost, workPort2);
clientSocket_B.getRemoteSocketAddress().toString();

returns a correct IP address of the WebServer.

Why is this happening?

Upvotes: 2

Views: 496

Answers (1)

Surojit
Surojit

Reputation: 1292

What you see 0:0:0:0:0:0:0:1 is the IPv6 equivalent of 127.0.0.1. This is because you have IPv6 enabled on your server and are establishing a connection to your server from the same machine.

You may be able to see the IPv4 address by forcing the client to use only the IPv4 protocol. On the other hand, it is most likely that your web server host uses an IPv4 internet address which you can see when you call -

Socket clientSocket_B = new Socket(WebServerHost, workPort2);
clientSocket_B.getRemoteSocketAddress().toString();

Upvotes: 2

Related Questions