Java 套接字 - 本地端口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13503929/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:00:44  来源:igfitidea点击:

Java Socket - Local Port

javasockets

提问by A.B.

I'm learning the socket programming with Java. I connect to a website using this statement:

我正在学习使用 Java 进行套接字编程。我使用以下语句连接到一个网站:

s = new Socket("www.nba.com", 80);

When i debug the application and look at the content of s, i see:

当我调试应用程序并查看 s 的内容时,我看到:

Socket[addr=www.nba.com/2.21.246.97,port=80,localport=7846]

1) I want to know where this localport 7846 comes from and what it exactly is.

2) if the IP address of the website is 2.21.246.97, why can't i connect to the website by just typing 2.21.246.97 in the address field of my browser ?

1) 我想知道这个本地端口 7846 来自哪里以及它到底是什么。

2)如果网站的IP地址是2.21.246.97,为什么我在浏览器的地址栏中输入2.21.246.97无法连接到网站?


Thanks


谢谢

采纳答案by ShyJ

It is a local socket port number. It is usually assigned by the system.

它是一个本地套接字端口号。它通常由系统分配。

See 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.

在客户端:客户端知道运行服务器的机器的主机名和服务器正在侦听的端口号。为了发出连接请求,客户端尝试在服务器的机器和端口上与服务器会合。客户端还需要向服务器标识自己,以便它绑定到将在此连接期间使用的本地端口号。这通常由系统分配。

As to the second question:

关于第二个问题:

I assume this IP address is what you get by your DNS server when you lookup www.nba.com(mine is different). The problem might be that the HTTP server at this address serves multiple virtual hosts and/or it cares about the Hostheader your browser sends. In your case it is the IP address instead of www.nba.com.

我假设这个 IP 地址是您在查找时通过 DNS 服务器获得的地址www.nba.com(我的不同)。问题可能是这个地址的 HTTP 服务器服务于多个虚拟主机和/或它关心Host你的浏览器发送的标头。在您的情况下,它是 IP 地址而不是www.nba.com.