Archived

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

Snash

Checking if a Socket is valid?

Recommended Posts

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
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.

cu,
Prefect

Share this post


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

int result = getsockopt(clientSocket,
SOL_SOCKET,
SO_CONNECT_TIME,
(char *)&connectTime,
(int*)&connectTimeSize);
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