For a TCP server with following structure:
main(){
socket();
bind();
listen();
while(1){
accept();
fork();
if(child)
Process;
}
}
It creates a new socket for each client and communicates with all clients using the same port. Thus, all sockets bind to the same port.
I came across following comments when reading the kernel code (2.6.33.5):
48/* There are a few simple rules, which allow for local port reuse by
49 * an application. In essence:
50 *
51 * 1) Sockets bound to different interfaces may share a local port.
52 * Failing that, goto test 2.
53 * 2) If all sockets have sk->sk_reuse set, and none of them are in
54 * TCP_LISTEN state, the port may be shared.
55 * Failing that, goto test 3.
56 * 3) If all sockets are bound to a specific inet_sk(sk)->rcv_saddr local
57 * address, and none of them are the same, the port may be
58 * shared.
59 * Failing this, the port cannot be shared.
60 *
So, for the TCP server above, is it the third rule which it matches?
There are 1 plus N sockets playing in this game.
1 The listening socket, which was passed to
bind()andlisten(). Only this socket is bound to the port on which the server listens.2 All the N connected sockets created by the N ‘processes’ of the clients connecting to the server, and being returned by
accept(). Those sockets are serving the connections to the clients. Such sockets do not listen in the sense the listening socket does.The rules you quoted apply to the listening socket only.
So if you only run one instance of your server the third rule does not apply, as it
bind()s only one socket tolisten()on the server’s port.