You are here

Get a free port on Unix in C/C++

As a client, you automatically get a free port when you open a connection. As a server, you can get a free port, too, but retrieving the port number is not very trivial. We need to know the port number since we are getting a random free port. If we don't know the port number, this server will be useless. This technique will be very useful for school projects, since you don't know what ports are free on the TA's computer.


Open a socket as usual.

int serverfd;
serverfd = socket(AF_INET, SOCK_STREAM, 0);

Bind with a zero port number. The OS will assign a free port.

sockaddr_in channel;
memset(&channel, 0, sizeof(channel));
channel.sin_family = AF_INET;
channel.sin_addr.s_addr = INADDR_ANY;
bind(serverfd, (sockaddr *) &channel, sizeof(channel));

It is often assumed that "channel" should now contain the port number, but in fact it doesn't. The port number should be retrieved by calling "getsockname".

socklen_t channellen;
getsockname(serverfd, (sockaddr*) &channel, &channellen);

Now we have the port number.

short portno;
portno = ntohs(channel.sin_port);




Awesome, thanks!

As I understand it, in your example channellen should be initialized to the size of the socketaddr structure before calling getsockname. If you don't, the port will still be always returned as 0.

Add new comment