Anon port selection

Janne Huttunen jahuttun at gmail.com
Fri Jan 8 11:02:58 UTC 2010


Hi!

The selection of anonymous port in FreeBSD seems to act
a bit weird (bug?). This was first observed on actual
use on FreeBSD 6.2, but I have verified that the it
behaves the same on a December snapshot of CURRENT too.

1. A process creates an UDP socket and sends a packet
   from it (at which point a local port is assigned
   for it).
2. Another process creates an UDP socket, sets
   SO_REUSEADDR (or SO_REUSEPORT) and sends a packet
   from it (at which point a local port is assigned
   for it).

Every now and then it happens that the second process
gets the same local port as the first one. If the
second process doesn't set the socket option this
won't happen. Note however, that the first process
does not have to cooperate in any way i.e. it does
not set any options.

Now, I'm fairly newbie when it comes to the FreeBSD
IP stack, but it seems to me that this phenomenon is
caused by the code in in_pcbconnect_setup(). If the
local port is zero the in_pcbbind_setup() is called
to select a port. That routine is called with the
local address set to the source address selected for
the outgoing packet, but when the port has been
selected, it is committed with INADDR_ANY as the
local address. Then when the second process in
in_pcbbind_setup() tries to check if the port is
already in use, it won't match the INADDR_ANY and
assigns the same port again.


More information about the freebsd-net mailing list