On Sun, 19 Sep 2010 12:27:08 +1200, Lawrence D'Oliveiro wrote: >> That's why Stevens recommends that all TCP servers use the >> SO_REUSEADDR socket option. > > I don’t think I’ve ever used that. It seems to defeat a safety mechanism > which was put in for a reason.
It was put in for the benefit of clients, to prevent them from selecting a port which they won't be able to use. At the point that the program calls bind(), the kernel doesn't know whether the program will call connect() or listen() next (i.e. whether it's a client or a server). Even if you set SO_REUSEADDR, you cannot create a connection which could be confused with an existing connection, i.e. one with the same source and destination address and port (BSD allows this provided that the previous connection is closed and the initial sequence number of the new connection exceeds the final sequence number of the previous connection). For a client, re-using the port would mean that any attempt to connect to the same port and address as an existing TIME_WAIT connection will fail with EADDRINUSE, so it should choose another port. This scenario is quite likely, as a client for a particular protocol will tend to connect to a specific remote port, and often to a small set of servers. But a server often has to use a specific port, and its clients will typically connect from ephemeral ports. Even if some clients insist on trying to use a specific source port (which will fail so long as the TIME_WAIT connections exist), the server can still serve other clients. -- http://mail.python.org/mailman/listinfo/python-list