views:

154

answers:

3

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.

alt text

A: 

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

Pierreten
How does this statement answer the question?
Hemant
what is your definition of a "site" ?
Adrien Plisson
+9  A: 

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.

Greg Hewgill
+1  A: 

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)

Yannick M.