[英]How to retrieve client's IP and PORT on the server socket end?
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. 我有一个基于java的套接字侦听器在桌面端运行,并且我有一个移动客户端,它可以与此套接字服务器连接而不会出现任何问题。 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
我从此链接中读取了用于多个连接检测的参考链接
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.
提到基于套接字服务器上检测到的客户端连接的IP和PORT,并且该连接对于每个连接都是唯一的。 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. 我读到了,我们可以调用
getpeername
来获取套接字服务器端上客户端连接的IP和PORT。 But, i couldn't see any such API available in Java and then found the below one. 但是,我看不到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? 有人可以告诉我,为什么我没有在套接字端使用上面的InetAddress API获得客户端的IP和PORT吗? Or Do I need to use different approach?
还是我需要使用其他方法?
When the server accept
sa connection you get a Socket
that represents that connection. 当服务器
accept
一个连接时,您将获得一个代表该连接的Socket
。 Socket
has a getInetAddress()
method that will return the remote's address, and a corresponding getPort()
method that will return the remote's port. Socket
具有将返回远程地址的getInetAddress()
方法和将返回远程端口的相应getPort()
方法。
For example: 例如:
Socket newSock = s.accept();
InetAddress addr = s.getInetAddress();
int port = s.getPort();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.