Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if socket is connected or not [duplicate]

I have an application which needs to send some data to a server at some time. The easy way would be to close the connection and then open it again when I want to send something. But I want to keep the connection open so when I want to send data, I first check the connection using this function:

bool is_connected(int sock) {     unsigned char buf;     int err = recv(sock,&buf,1,MSG_PEEK);     return err == -1 ? false : true; } 

The bad part is that this doesn't work. It hangs when there is no data to receive. What can I do? How can I check if the connection is still open?

like image 379
opc0de Avatar asked Sep 13 '12 08:09

opc0de


People also ask

How do you check if socket is connected or not?

If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.

How socket is connected?

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to. An endpoint is a combination of an IP address and a port number.


1 Answers

Don't check first and then send. It's wasted effort and won't work anyway -- the status can change between when you check and when you send. Just do what you want to do and handle the error if it fails.

To check status, use:

int error_code; int error_code_size = sizeof(error_code); getsockopt(socket_fd, SOL_SOCKET, SO_ERROR, &error_code, &error_code_size); 
like image 187
David Schwartz Avatar answered Oct 13 '22 14:10

David Schwartz