views:

189

answers:

2

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!

A: 

Is this what you are looking for?

u32 secure_ipv4_port_ephemeral(__be32 saddr, __be32 daddr, __be16 dport);

Nikolai N Fetissov
Not quite. The inet_csk_get_port is more what I was after. Thanks for your help though!
Ntek
+3  A: 

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.

Chris Jester-Young
This is exactly what I'm looking for. Thanks! Now, I just have to figure out how to call bind() to get a random port and not a specific one.
Ntek
@Will: You didn't hear this from me, but if you bind to port 0, chances are excellent that it will be treated as an unbound port. (But if you can just make your code not bind at all, then even better.)
Chris Jester-Young
I try to implement bind(2) using just the sample code on the man pages and try to pass a zero into argument one, but then i get the error: Socket operation on non-socket. Is there any sample code I can view for the bind() with passing port 0 to get the random port algorithm you pointed out to fire?
Ntek
@Will: I wrote a sample test program showing that binding with port 0 works (comment out the binding lines, and see how the same thing happens): http://codepad.org/AtjvJaFb
Chris Jester-Young
@Will - The 1st argument is the socket. You want to set the port to 0 in the 2nd argument, the sockaddr struct. Something like myAddr.sin_port = htons(0);
Duck
@Chris: Thanks! This is by far the best help I've ever gotten on the web. I appreciate your time on this one. It's exactly what I needed as an example. I used this code and put a test printk to see that the bind was hitting the function you mentioned and now have a better understanding of what all is happening here. Thanks again. Fantastic help!
Ntek