tags:

views:

83

answers:

1

Hi,

Any body knows how is the port number bound with a socket in detail and how is the port used to forward the packet received in transport layer to a socket which is reading on this port?

thanks.

+2  A: 

The application binds to a local IP address and port using the bind() function. The remote IP address and port is determined by the other end of the connection at the time a connection is established.

In the kernel, at the time a tcp connection is established the socket is put into a hash table based on data including the local address, local port, remote address, and remote port. When an incoming tcp segment arrives, these values are extracted from the header and used to look up the corresponding socket in the hash table. In Linux this lookup occurs in the function inet_lookup_established(). A similar function, inet_lookup_listener() is used to look up a listening socket from a different hash table for a new connection; in that case the remote IP address and port are not used.

mark4o
thank you very much. it is very helpful to me. Some more questions:1. so the hashtable belongs to TCP layer2. after getting the socket using inet_lookup_established(), how the packet is forwarded to the thread to which the socket belongs in detail.3. if the socket does not read the inbound packet timely, will the socket buffer overflow and how the kernel handle it if overflow occurs.Thanks!
Guoqin
1. In Linux it is the IPv4 or IPv6 layer. 2. The data goes to the socket receive buffer in the kernel; see source code for `tcp_data_queue()` for details. The data is then transferred to the application when it calls `recv()` or a similar function. 3. The sender can only send data in the receive window so it will have to slow down it is not being read fast enough, and the receive buffer cannot overflow. See RFC 793 for details.
mark4o