Java 如何在服务器套接字端检索客户端的 IP 和 PORT?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21655187/
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 retrieve client's IP and PORT on the server socket end?
提问by Stella
I have a socket listener java based running on the desktop end and I have a mobile client, which is able to connect with this socket server without any issues. I want to have the socket connection established for each client separately, when client is trying to access new connection. I read from this link, Reference link for multiple connection detection
我有一个基于桌面端运行的套接字侦听器 java,我有一个移动客户端,它能够毫无问题地连接到这个套接字服务器。当客户端尝试访问新连接时,我想分别为每个客户端建立套接字连接。我从这个链接中阅读了多连接检测的参考链接
about how socket can differentiate for multiple connections. It is mentioned that based on the Client connection's IP and PORT detected on the socket server and the connection is made unique for each connection. Client PORT will differ for each connection. I read that, we can call getpeername
to get the client connection's IP and PORT on the socket server end. But, i couldn't see any such API available in Java and then found the below one.
关于套接字如何区分多个连接。提到基于在套接字服务器上检测到的客户端连接的 IP 和端口,并且每个连接的连接都是唯一的。每个连接的客户端端口都会不同。我读到了,我们可以getpeername
在套接字服务器端调用以获取客户端连接的 IP 和端口。但是,我在 Java 中看不到任何此类 API,然后找到了以下 API。
ServerSocket server = new ServerSocket(8080);
System.out.println("server.getInetAddress();: " + server.getInetAddress());
But, It is returning always server.getInetAddress():- 0.0.0.0/0.0.0.0
when the mobile client (Simulator) is calling this socket.
但是,server.getInetAddress():- 0.0.0.0/0.0.0.0
当移动客户端(模拟器)调用这个套接字时,它总是返回。
Could someone advise me, why I'm not getting the client's IP and PORT using the above InetAddress API on the socket end? Or Do I need to use different approach?
有人可以告诉我,为什么我没有在套接字端使用上述 InetAddress API 获取客户端的 IP 和端口?或者我需要使用不同的方法吗?
回答by Jim Garrison
When the server accept
s a connection you get a Socket
that represents that connection. Socket
has a getInetAddress()
method that will return the remote's address, and a corresponding getPort()
method that will return the remote's port.
当服务器accept
sa 连接时,您会得到一个Socket
代表该连接的。Socket
有一个getInetAddress()
返回远程地址的getPort()
方法,以及一个返回远程端口的相应方法。
For example:
例如:
Socket newSock = s.accept();
InetAddress addr = s.getInetAddress();
int port = s.getPort();