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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With