Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting unused port number in C dynamically when running server process

Tags:

c

linux

sockets

I am using C and writing a client-server program, and I would like to get an unused port number to run my server process. My server code is like this:

getaddrinfo()
socket()
bind()
listen
while(1)
  accept()

I need to provide the unused port addr to the bind() call. But I do not want to pass the port number via command line while starting the server process. The port number should be got via a socket call, and I need to use that to start my client process. Is there any socket call which would help me get an unused port dynamically in C ?

like image 251
Vin Avatar asked Sep 23 '11 15:09

Vin


1 Answers

Just bind() your socket setting sin_port to 0 in sockaddr_in. System will automatically select unused port. You can retrieve it by calling getsockname().

But I don't have any idea how to pass it to client, except printing it and using as command-line parameter for client program.

like image 193
blaze Avatar answered Oct 13 '22 00:10

blaze