开发者

How does a TCP/IP packet reach to a specific server socket?

开发者 https://www.devze.com 2022-12-14 17:28 出处:网络
I understand that when a TCP client connects to a server, it automatically uses a unused local port unless specified explicitly. On the server side, we have a listening socket which creates a new sock

I understand that when a TCP client connects to a server, it automatically uses a unused local port unless specified explicitly. On the server side, we have a listening socket which creates a new socket whenever a new connection is accepted.

But all server sockets use same local port (I checked this with netstat). My question is how does a packet sent from client reaches to a specific socket on server when all server side sockets are communicating over same IP address and local port?

Below is a telnet snapshot showing that my tcp/ip echo server is using same address and port for 2 different connections.开发者_如何学Go

How does a TCP/IP packet reach to a specific server socket?


When you make a connection from a client to a server, TCP on the server knows the address and port of the client. Each individual connection is identified and distinguished by the 4-tuple (client_ip, client_port, server_ip, server_port).

In your netstat display, the combination of local address and remote (foreign) address uniquely identifies the connection. The foreign addresses for the two highlighted connections are different.


This is basically the difference between inbound and outbound connections.

On inbound connections the server socket would be bound to and listening on a given ip:port. Incoming connections get accepted on new sockets with the same ip:port, as they are accepted from the listening server socket.

When using netstat, you should see the server socket's ip:port in the Listening state (for TCP connections) and multiple ip:port in Established state for incoming connections that were accepted on new sockets.

Outbound connections only allow unbound ports to be used. You can specify them manually, or have one chosen at random by the tcp/ip stack. (An exception to this would be when using SO_REUSEADDR, which allows you to bind to a bound port that is still in TIME_WAIT state)


On the server, only one open port just means you're running a single site.

0

精彩评论

暂无评论...
验证码 换一张
取 消