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