9
votes

Anyone know what function or file in linux holds the algorithm that finds a random port to use for the bind() system call? I'm hunting all over and cannot find the method that contains this algorithm in the Linux source.

Thanks!

3
Am I missing something here? bind(2) is for assigning specific, not random, port to a socket. Are you talking about ephemeral ports?Nikolai Fetissov
@Nikolai: +1 Yes, I presume that's exactly what the OP is referring to.Chris Jester-Young

3 Answers

6
votes

It's a long and complicated piece of code, which I'm not keen to try to grok. :-)

Have a look at the inet_csk_get_port function (in net/ipv4/inet_connection_sock.c) for TCP, and udp_lib_get_port (in net/ipv4/udp.c) for UDP. It's valid, at least, for 2.6.31, though it may vary for different versions.

0
votes