3

There have been other questions regarding the subject of verifying the accessibility and accessibility of socket ports.

How would one go about looking for a port to listen on dynamically in C/C++?

The basic process I'm trying to accomplish is this:

  1. Client starts
  2. Client finds open port XYZ and listens on it.
  3. Client transmits a basic 'I Am Here' message via UDP Datagrams to a server with the port information
  4. Client and Server can communicate.

I know you can accomplish something like this if you pick an arbitrary port number and try binding to it. If it fails, increment the number and try again until you get a successful 'bind'.

Is there a more elegant way to do this? It seems kind of hacky.

Community
  • 1
  • 1
Sean Madden
  • 1,069
  • 2
  • 10
  • 22
  • Sending port numbers inside the message will break clients behind a NAT firewall, so don't do it. Just have the server use the port that the message arrived from. – Zan Lynx Jun 16 '10 at 20:22
  • @David Windows right now, but hopefully it will eventually be portable to linux as well. – Sean Madden Jun 16 '10 at 20:31

1 Answers1

13

If you bind to port 0, a random port will be allocated. Then getsockname() may be used to find out the actual port used.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
  • 1
    That will work. But Sean, do not send the port number in a UDP message. That will break NAT. Just have the server respond to the port that the message arrived from. – Zan Lynx Jun 16 '10 at 20:21
  • @Zan NAT isn't going to be an issue. It's only going to be used between elements on the same network segment. – Sean Madden Jun 16 '10 at 20:23
  • +1 this is also used by FTP servers when client is in passive mode – INS Jun 16 '10 at 20:41