Java 如何找到连接到服务器的客户端的 IP 地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1840420/
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
How to find the IP Address of Client connected to Server?
提问by Kevin Boyd
My client pc is connected to as server pc via sockets over Ethernet, How do I find the IP of this client from the server side code.
The server is dishing out one socket per client in a new Thread.
When I do a csocket.getLocalAddress().toString()
on the client socket I still get the Server IP address. (csocket
is the socket that the Server has spawned upon a now client connection and passed it to a new Thread).
我的客户端 pc 通过以太网上的套接字连接到服务器 pc,如何从服务器端代码中找到该客户端的 IP。
服务器在一个新线程中为每个客户端分配一个套接字。
当我csocket.getLocalAddress().toString()
在客户端套接字上执行 a时,我仍然获得服务器 IP 地址。(csocket
是服务器在现在的客户端连接上产生并将其传递给新线程的套接字)。
采纳答案by jheddings
I believe you want to use the remote addressinstead:
我相信您想改用远程地址:
csocket.getRemoteSocketAddress().toString();
回答by erickson
Use getRemoteSocketAddress()
instead.
使用getRemoteSocketAddress()
来代替。
回答by Alex Shnayder
I think you might be looking for the getInetAddressmethod of the Socketobject.
我想您可能正在寻找Socket对象的getInetAddress方法。
回答by Ahmad Aghazadeh
Use this code :
使用此代码:
String ip=(((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()).toString().replace("/","");