[patch] Set SO_REUSEADDR on outgoing TCP connections

Maxim Dounin mdounin at mdounin.ru
Thu Apr 10 15:40:14 UTC 2014


On Wed, Apr 09, 2014 at 04:53:04PM +0100, Marek Majkowski wrote:

> Usually, when establishing a connection the kernel allocates outgoing
> TCP/IP port automatically from an ephemeral port range. Unfortunately
> when selecting the outgoing source IP (using bind before connect) the
> kernel needs a unique port number. As the result it can only establish
> a single outgoing connection from a single source port. This can cause
> problems with a large number of outgoing proxy connections - it's
> possible for the kernel to run out free ports in the ephemeral range.
> The situation can be improved - TCP/IP allows any number of
> connections to share outgoing TCP/IP port and host pair assuming the
> destination addresses differ.
> This patch sets a SO_REUSEADDR flag on the connections that use bind
> before connect to select ougoing source address. This will allow the
> kernel to reuse source port numbers, given that the destination
> addresses are different.
> The patch will work perfectly well assuming there aren't too many
> connections to one destination address and port. If that happens the
> kernel may randomly allocate an outgoing port number that is already
> used for a given destination and attempt to connect() will fail with
> EADDRNOTAVAIL. This is fairly easy to detect, and we can just retry
> connecting again, using another random source port allocated by the
> kernel.

While it may be interesting approach to overcome the limitation, I 
don't think that this is something that should be done by clients 
in real life.  I think it's something kernel should care about, 
not clients.

>From practical point of view, trivial solutions are to avoid 
bind() or use multiple addresses for bind().

Maxim Dounin

More information about the nginx-devel mailing list