localhost
localhost

Reputation: 1273

Get remote tcp connection's ip address in java?

I've used the well-known and excellent Knock Knock server tutorial as a way to learn java networking. I have tried to find out the ip address of the connected client using socket.getInetAddress(), but it always returns the ip of my router, 192.168.1.254, presumably because the connection is bouncing through there. Is there any way to get the correct ip of the remote client that's connected to a tcp socket?

Upvotes: 2

Views: 4653

Answers (1)

Nikhar
Nikhar

Reputation: 1074

Try this:

ServerSocket sSock;
Socket cSock;

sSock = new ServerSocket(port_number);
cSock = sSock.accept();
System.out.println(cSock.getRemoteSocketAddress()+" connected\n");

it will print whole socket address of the connected client like this:

/127.0.0.1:1878 connected

Upvotes: 4

Related Questions