java ServerSocket + 客户端 Socket - 如何获取客户端的 IP 地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15421592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ServerSocket + client Socket - how do I get IP address of client?
提问by Alex Blundell
I have a ServerSocket instance which is listening for connections. When a client connects to it, I would like to get the IP of the connected socket, but can't seem to find the right method to do so.
我有一个正在侦听连接的 ServerSocket 实例。当客户端连接到它时,我想获取连接套接字的 IP,但似乎无法找到正确的方法。
public void start() {
listenSocket = new ServerSocket(port);
connectionSocket = listenSocket.accept();
}
I've tried calling the following with no luck:
我试过在没有运气的情况下调用以下内容:
connectionSocket.getLocalAddress();
connectionSocket.getInetAddress.getHostAddress();
listenSocket.getLocalSocketAddress();
None of the above return the correct IP. They either return "/0:0:0:0:0:0:0:1%0" or "0.0.0.0".
以上都没有返回正确的IP。它们要么返回“/0:0:0:0:0:0:0:1%0”或“0.0.0.0”。
What am I doing wrong?
我究竟做错了什么?
回答by Shmil The Cat
connectionSocket.getRemoteSocketAddress();