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.
serverfd = socket(AF_INET, SOCK_STREAM, 0);
Bind with a zero port number. The OS will assign a free port.
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".
getsockname(serverfd, (sockaddr*) &channel, &channellen);
Now we have the port number.
portno = ntohs(channel.sin_port);