简体   繁体   English

在java中获取远程tcp连接的ip地址?

[英]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.我使用了著名且优秀的Knock Knock 服务器教程作为学习 Java 网络的一种方式。 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.我试图使用 socket.getInetAddress() 找出连接客户端的 IP 地址,但它总是返回我的路由器的 ip,192.168.1.254,大概是因为连接在那里反弹。 Is there any way to get the correct ip of the remote client that's connected to a tcp socket?有没有办法获得连接到tcp套接字的远程客户端的正确IP?

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 /127.0.0.1:1878 已连接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM