Hi guys, I'm doing some network programming on the school Linux computers, and I need some help with sockets. Essentially, I have two programs: one that will scan for an open port, and one that will connect to the open port the other one found. My problem is that if I open a socket on a port and find out it's open, even after I close it, the other program can't listen on that port because it hasn't finished it's linger time. And for the second program that does the connecting, I'm using the Thrift network, so I have no control over HOW it connects to the socket. I just give a port number and that's it.
So I'm really stuck here. In C/C++, how can I go about finding an open port on my machine, yet still be able to connect to that port from another program? Any help would be much appreciated.
Sounds a bit like a nonsense to me. A server port (if that's what the OP calls 'open port') is normally designed to serve multiple clients. Even if the server can only handle one connection at a time, clients should be able to connect to the server without any waiting time. The server port won't get in a TIME_WAIT or FIN_WAIT state, only the client port may. An exception would be if two clients on the same machine would bind to the same client socket. But clients would normally not explicitly bind their socket to a specific port.
Agreement with Richard.J. TCP states like TIME_WAIT apply to connections, not ports. And a connection is uniquely identified by the 5-tuple of the two IP addresses of the endpoints, the two ports of the endpoints, and the protocol (here, TCP). Each endpoint is responsible for maintaining its own view of the state of the connection, which is why one endpoint might get to TIME_WAIT and the other to CLOSE_WAIT.
The only way that TIME_WAIT might be an issue is if a client tries to reestablish a previously closed connection to a server using the exact same outgoing port number (i.e., client-side port number) to connect to the server's listening port. This is avoided in all network stacks through use of ephemeral ports, unless usage of ephemeral ports is explicitly overridden in the client code (for example, by inappropriate use of bind() on the client side).