1

Is there an idiomatic way to specify a specific address to bind to, but a random port?

In my application, I open a few dozen connections. I call bind() before connect() so that I can specify the IP address that the connection should be established with. However, I have to find an open port myself. It works fine for now, but it could become an issue if I need to open thousands of connections, as finding an open port will become slower and slower

int fd;
struct sockaddr_in addr;

fd = socket(AF_INET, SOCK_STREAM, 0);

while (TRUE)
{
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("192.168.0.1");
    addr.sin_port = htons((rand() % 65000) + 1);

    if (bind(fd, (struct sockaddr *)&addr, sizeof (struct sockaddr_in)) == 0)
        break;
}

I considered writing my own "port management" system, but I figured I would try to see if the OS already has a feature before going ahead and doing that

dreadiscool
  • 1,598
  • 3
  • 18
  • 31
  • I won't flag it as duplicate as it is referring to a different language, but essentially the same: http://stackoverflow.com/questions/1365265/on-localhost-how-to-pick-a-free-port-number – Eugene Sh. Aug 12 '15 at 19:57

1 Answers1

6

Just set addr.sin_port to zero. The OS will pick one for you.

After the bind, you can call getsockname to find out which port you were bound to.

dbush
  • 205,898
  • 23
  • 218
  • 273