This topic is now archived and is closed to further replies.


Checking if a Socket is valid?

Recommended Posts

Snash    122
Hi. Is there anyway I can check if the clients socket is valid? For example. The client connects to the server. The client quits, and the server checks if the clients SOCKET is still valid. If I do a send, to a client that has disconnected, it returns a SOCKET_ERROR, but I don''t want to send, I just want to check if the SOCKET is valid. Anyway to do this? thanks for your time.

Share this post

Link to post
Share on other sites
Prefect    373
recv() on a disconnected socket returns 0.
It also makes sense to assume that if recv() returns -1 with an error code other than EAGAIN or EINTR, something has gone wrong with the socket and it should be closed.

If you put your socket in the read fd_set for select(), the socket will be flagged when it''s disconnected, so disconnection handling is pretty straightforward actually.


Share this post

Link to post
Share on other sites
Dire.Wolf    122
int connectTime = 0;
int connectTimeSize = sizeof(connectTime);

int result = getsockopt(clientSocket,
(char *)&connectTime,
if(err == SOCKET_ERROR)
// error

If the socket isn''t connected getsockopt will return SOCKET_ERROR letting you know that the connection is closed. Also, when you call closesocket() you should follow that up by setting the socket handle to INVALID_SOCKET;

Hope this helps.

Share this post

Link to post
Share on other sites