Java 套接字 - 本地端口

标签 java sockets

我正在学习使用 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/

相关文章:

java - 仅列出 s3 存储桶中的子文件夹

java - 使用 Arraylist 追加序列

linux - Winsock2 listen() 是如何阻塞的?

java - 是否应该在支持套接字关闭之前关闭 Java 流?

C++ HTTP/HTML 套接字问题

java - 从 JAVA 生成的 PDF 使用 Jasper Reports 损坏

java - spring 2.5中使用MultipartFile上传文件时出现空值

python - 从 python 中的 Twisted 协议(protocol)获取裸套接字 fd?

java - 为多个客户端打开多个服务器套接字端口

java - 动态可编辑复选框