user3770392
user3770392

Reputation: 473

two (wrong) connections on a socket that uses listen(1)

I'm developing two applications in C++ that use C Linux socket calls, a server and a client. The server listens on a specific port A and retrieves a connection using the accept function. I'm using int result = ::listen(mySocketFileDescriptor, 1); limiting the maximum connections to 1. By the way, in the server I'm using the SO_REUSEADDR option to reuse the socket for other reasons.

If there are multiple disconnections/connections from the client, sometimes strange behaviours happen: for instance, the client successfuly connects to the server but then when it sends data, the server doesn't receive anything.

In the client application I connect to port A, using a Linux auto-assigned port, let's call it B. Using netstat I've discovered that the client is connected to the server to the port A both from a socket that uses the port B and from another one using another port C. I've debugged and I've seen that the server reads from the socket that uses B while the client writes on the socket that uses C.

Any idea about the cause of this behaviour?

Apart from any possible logical problem that my code may have, is it possible to make the server always discard an old connection when a new one is established? is there any option I can set on it?

Thank you in advance!

Upvotes: 0

Views: 473

Answers (2)

John Bollinger
John Bollinger

Reputation: 180286

It is not straightforward for the machine at one end of a network connection to recognize that the other end has disconnected. In particular, it is very difficult to do so if the remote end severs the connection abruptly, rather than properly closing it.

Furthermore, nothing inherently prevents the same two machines from establishing multiple simultaneous connections. If you want to restrict that to just one, then your server needs to track which client(s) it is currently connected to, and it must be prepared to service multiple connections at the same time, so as to recognize when a new connection is established by an existing client. That requires either multiplexing (e.g. with use of select()) or multiprocessing. Then, if it receives a new connection from a client that already has one, the server halts handling of the old connection and closes it.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409186

You need to read the listen manual page more thoroughly, because the "limit" is not the max number of connections that can be made to that socket, it's the limit of the number of connections that can attempt to connect simultaneously before you call accept. Once you call accept another connection can be made.

The "standard" value in many examples is 5, and yet those servers can handle hundreds of connections.

Upvotes: 2

Related Questions