简体   繁体   中英

Getting unused port number in C dynamically when running server process

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.

That would be a huge race condition . Imagine this sequence of events:

  1. Your code uses the (non-existant) getNextFreePort() call.
  2. Another process creates a new socket without specifying a port, getting "your" number assigned to it.
  3. You try to bind() , which fails with "address in use".

This is why servers tend to have "well-known" addresses, since that's needed in order for a client to know where it should connect.

Also, unless I'm misunderstadning, you seem to expect the client to be able to call getNextFreePort() when starting, and then magically get the port number that server has already gotten, and used? That doesn't make a lot of sense, so hopefully I'm misunderstanding you.

Since you're on Linux/Unix, this is exactly a situation that the RPC portmapper was designed to solve. Your server bind() s to an unused port (port 0), then registers the resulting actual port (fetched with getsockname() with the portmapper by application/service name.

Clients then query portmapper on its known port, asking for what port that named service is actually running on.

portmapper RPC isn't as popular as it used to be

If servers and clients are on the same box:

Another alternative is to use some sort of naming scheme for a shared file (create a temporary file /tmp/servport.xxxxx), replacing xxxxx with the port.

Or you could create a shared memory segment that the server stashes its port into. Clients would attach to the same shared memory, read the port, and connect as normal.

Or your server could create a unix domain socket on a known/shared path, and clients could connect to that, asking for what port the server is on. (obviously you could just do all IPC this way if they are both local!)

Lots of options with IPC...

如果将()绑定到随机或不可预测的地址+端口号,则客户端可能会在查找服务器并连接到服务器时遇到一些困难。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM