我正在学习使用 Java 进行套接字编程。 我使用以下语句连接到网站:
s = new Socket("www.nba.com", 80);
当我调试应用程序并查看 s 的内容时,我看到:
Socket[addr=www.nba.com/2.21.246.97,port=80,localport=7846]
1)我想知道这个localport 7846是从哪里来的,到底是什么。
2) 如果网站的 IP 地址是 2.21.246.97,为什么我在浏览器的地址栏中输入 2.21.246.97 无法连接到网站?
谢谢
最佳答案
它是本地套接字端口号。通常由系统分配。
参见 What is a Socket? .
On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.
关于第二个问题:
我假设这个 IP 地址是您在查找 www.nba.com
时通过 DNS 服务器获得的地址(我的不一样)。问题可能是此地址的 HTTP 服务器服务于多个虚拟主机和/或它关心浏览器发送的 Host
header 。在您的情况下,它是 IP 地址而不是 www.nba.com
。
关于Java 套接字 - 本地端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503929/