获取Socket尝试连接的ServerSocket的地址/端口? (JAVA)

时间:2015-06-09 20:08:17

标签: java sockets

我不能很好地说出来,所以让我举个例子。 如果我的代码是:

Socket socket = new Socket("1.2.3.4", 80);

然后我运行两个方法,如:

System.out.println(socket.getAddressOfHost());
System.out.println(socket.getPortOfHost());

我希望它返回:

1.2.3.4
80

这可能吗?这些方法的名称是什么?

1 个答案:

答案 0 :(得分:0)

Socket连接到服务器后,可以使用Socket.getInetAddress()Socket.getRemoteSocketAddress()方法检索这些值:

InetAddress addr = socket.getInetAddress();
// InetAddress does not expose port numbers...
System.out.println(addr.getHostAddress());
System.out.println(addr.getHostName());

InetSocketAddress sockaddr = (InetSocketAddress) socket.getRemoteSocketAddress();
InetAddress addr = sockaddr.getAddress();
System.out.println(addr.getHostAddress());
System.out.println(addr.getHostName());
System.out.println(sockaddr.getPort());

有关详细信息,请参阅Socket documentation