nat与tcp

zhiihiu上的一篇,讲tcp与nat原理的,写的很好:穿透工具的原理与开发实战

stackoverflow上一篇:How does the socket API accept() function work?

How does accept work? How is it implemented? There's a lot of confusion on this topic. Many people claim accept opens a new port and you communicate with the client through it. But this obviously isn't true, as no new port is opened. You actually can communicate through the same port with different clients, but how? When several threads call recv on the same port, how does the data know where to go?

下面是高赞回答:

 

Your confusion lies in thinking that a socket is identified by Server IP : Server Port. When in actuality, sockets are uniquely identified by a quartet of information:

Client IP : Client Port and Server IP : Server Port

So while the Server IP and Server Port are constant in all accepted connections, the client side information is what allows it to keep track of where everything is going.

Example to clarify things:

Say we have a server at 192.168.1.1:80 and two clients, 10.0.0.1 and 10.0.0.2.

10.0.0.1 opens a connection on local port 1234 and connects to the server. Now the server has one socket identified as follows:

10.0.0.1:1234 - 192.168.1.1:80  

Now 10.0.0.2 opens a connection on local port 5678 and connects to the server. Now the server has two sockets identified as follows:

10.0.0.1:1234 - 192.168.1.1:80  
10.0.0.2:5678 - 192.168.1.1:80

zhihu上另外一个回答:

A1: 只有公网IP才可以在互联网上被用户访问,而服务器的私有IP无法被互联网用户访问,假设公司的公网IP = 1.1.1.1,服务器IP = 10.0.0.1,端口映射将产生以下静态表项:

 

NAT设备一旦接收目的IP + 端口号为1.1.1.1:443的报文,就会转换为10.0.0.1:443,并将转换好的IP报文继续转发给服务器。

链接:https://www.zhihu.com/question/270396590/answer/38229019

猜你喜欢

转载自www.cnblogs.com/xiang-yin/p/12111673.html
NAT