Naoum Mandrelas
Naoum Mandrelas

Reputation: 258

Some questions around sockets and accept()

Lets say that we have created a socket with socket(), then we used bind() and listen(). Then we use accept() to wait for client requests, after a client is connected if we shutdown the server (for example we ctrl+c the process).

  1. Is the client still connected to the port ?
  2. Can we somehow reestablish connection to the socket ?
  3. Is this a client-side issue as well ? Or does recvfrom() wait for someone to bind back to the socket ?

Upvotes: 4

Views: 89

Answers (2)

user207421
user207421

Reputation: 310884

Is the client still connected to the port?

The client will get a connection reset when reading on Windows, or an EOS when reading under *nix, or a connection reset when writing.

Can we somehow reestablish connection to the socket?

To the port. The client can try to reconnect, but it won't succeed until the server is running and listening. The server can't do anything about it after it restarts.

Is this a client a client-side issue as well?

Yes, see above.

Or does recvfrom() wait for someone to bind back to the socket?

Certainly not.

NB You should be using recv() for stream sockets. You don't need the source-address information recvfrom() gives you, if indeed it does, because it's already available via getpeername() on the socket.

Upvotes: 2

John Zwinck
John Zwinck

Reputation: 249133

I am going to assume you're using TCP.

If we shutdown the server:

  1. Is the client still connected to the port?

    No. The operating system on the server side will have noticed that the server terminated, and will have closed the connection, sending a packet to the client which ends the connection. Even if this does not happen (e.g. the network fails), the connection is no longer usable, and the first time the client sends something, it will realize the connection was lost. Some programs use TCP Keep-Alive or send heartbeat messages to make sure they notice if the server goes away.

  2. Can we somehow reestablish connection to the socket?

    No. The client needs to establish a new connection.

  3. Is this a client-side issue as well? Or does recvfrom() wait for someone to bind back to the socket?

    recvfrom() does not wait in such a way. The server cannot "reconnect" or "rebind" in the way you are implying. The client will need to respond to the disconnection by explicitly reconnecting.

Upvotes: 3

Related Questions