I have a TCP connection. Server just reads data from the client. Now, if the connection is lost, the client will get an error while writing the data to the pipe (broken pipe), but the server still listens on that pipe. Is there any way I can find if the connection is UP or NOT?
-
3I think you should clarify wether you are developing for windows or linux/unix ..– nairdaenNov 10, 2010 at 7:14
-
When sending results in an error, you should first check what error it actually is and then decide if that is a recoverable error (could it fix on its own maybe?) or if it means your connection is dead for sure. And if is dead for sure, close the socket. If you can still get any traffic through, the other side will see the socket has been closed. If you cannot get any traffic through, you are lost anyway. In that case the only way the other side can notice is by sending something itself that should trigger a reply and if there is no such reply, then the other side is dead.– MeckiJul 18, 2017 at 15:57
12 Answers
You could call getsockopt just like the following:
int error = 0;
socklen_t len = sizeof (error);
int retval = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &error, &len);
To test if the socket is up:
if (retval != 0) {
/* there was a problem getting the error code */
fprintf(stderr, "error getting socket error code: %s\n", strerror(retval));
return;
}
if (error != 0) {
/* socket has a non zero error status */
fprintf(stderr, "socket error: %s\n", strerror(error));
}
-
16It will not detect a silently broken socket though. A common scenario is that a NAT gateway inbetween times out the connection (and noone gets notified) - to detect that , as others have said, you'll have to send something periodically either by implementing some form of heartbeats on your application protocol, or atleast use TCP_KEEPALIVE– nosNov 10, 2010 at 8:15
-
anyone wondering, I think
SOL_SOCKET
stands for 'socket option level: socket' andSO_ERROR
is the last error code on the socket.– n611x007Aug 30, 2013 at 12:05 -
1This only returns the last error. It doesn't detect pending errors. Dec 20, 2015 at 6:40
-
13ofc it doesn't detect errors that hasn't happened yet, it's not a time machine Mar 5, 2016 at 12:33
-
8strerror(retval) seems incorrect, at least on Linux. Man page for getsockopt says "On success, zero is returned. On error, -1 is returned, and errno is set appropriately". So it should be strerror(errno) Nov 28, 2016 at 13:45
The only way to reliably detect if a socket is still connected is to periodically try to send data. Its usually more convenient to define an application level 'ping' packet that the clients ignore, but if the protocol is already specced out without such a capability you should be able to configure tcp sockets to do this by setting the SO_KEEPALIVE socket option. I've linked to the winsock documentation, but the same functionality should be available on all BSD-like socket stacks.
-
Thanks for you time. I considered SO_KEEPALIVE option, but the default time to activate KeepAlive probes is 2 hours in linux. If I bring this down to seconds, other applications might be affected. I will give it a shot anyways :) Nov 10, 2010 at 8:44
-
1This is why its common to resort to an application level ping packet that the server can send whenever the connection has been quiet for some interval. If - like in http - you can't send data without receiving a client request, then you have no option but to simply close connections that have been silent for "too long" and rely on the clients to reconnect when required. Nov 10, 2010 at 9:41
-
6@Blacklabel Linux (and others) allow you to set the keepalive timeout per socket, see the TCP_KEEPIDLE socket option in
man 7 tcp
– nosNov 10, 2010 at 20:12
TCP keepalive socket option (SO_KEEPALIVE) would help in this scenario and close server socket in case of connection loss.
-
5It wouldn't close anything. It would give an error on the next send or receive, but the socket remains open. Dec 20, 2015 at 6:34
Very simple, as pictured in the recv.
To check that you will want to read 1 byte from the socket with MSG_PEEK
and MSG_DONT_WAIT
. This will not dequeue data (PEEK
) and the operation is nonblocking (DONT_WAIT
)
while (recv(client->socket,NULL,1, MSG_PEEK | MSG_DONTWAIT) != 0) {
sleep(rand() % 2); // Sleep for a bit to avoid spam
fflush(stdin);
printf("I am alive: %d\n", socket);
}
// When the client has disconnected, this line will execute
printf("Client %d went away :(\n", client->socket);
Found the example here.
There is an easy way to check socket connection state via poll
call. First, you need to poll socket, whether it has POLLIN
event.
- If socket is not closed and there is data to read then
read
will return more than zero. - If there is no new data on socket, then
POLLIN
will be set to 0 inrevents
- If socket is closed then
POLLIN
flag will be set to one and read will return 0.
Here is small code snippet:
int client_socket_1, client_socket_2;
if ((client_socket_1 = accept(listen_socket, NULL, NULL)) < 0)
{
perror("Unable to accept s1");
abort();
}
if ((client_socket_2 = accept(listen_socket, NULL, NULL)) < 0)
{
perror("Unable to accept s2");
abort();
}
pollfd pfd[]={{client_socket_1,POLLIN,0},{client_socket_2,POLLIN,0}};
char sock_buf[1024];
while (true)
{
poll(pfd,2,5);
if (pfd[0].revents & POLLIN)
{
int sock_readden = read(client_socket_1, sock_buf, sizeof(sock_buf));
if (sock_readden == 0)
break;
if (sock_readden > 0)
write(client_socket_2, sock_buf, sock_readden);
}
if (pfd[1].revents & POLLIN)
{
int sock_readden = read(client_socket_2, sock_buf, sizeof(sock_buf));
if (sock_readden == 0)
break;
if (sock_readden > 0)
write(client_socket_1, sock_buf, sock_readden);
}
}
-
1This is a good start, but what the OP was asking is about errors... if a socket generates an error you get a
POLLERR
,POLLHUP
,POLLRDHUP
, orPOLLNVAL
. If yourrevents
has any one of those flags set, then you know that the socket is now disconnected and you can get right of it. Also, you should notwrite()
unless the socket returnsPOLLOUT
. Finally, at least under Linux, it'sPOLLIN
(no_
). Find a fully functional version around line 7000 in github.com/m2osw/snapcpp/blob/master/snapwebsites/… Jan 23, 2017 at 5:52
I had a similar problem. I wanted to know whether the server is connected to client or the client is connected to server. In such circumstances the return value of the recv function can come in handy. If the socket is not connected it will return 0 bytes. Thus using this I broke the loop and did not have to use any extra threads of functions. You might also use this same if experts feel this is the correct method.
-
1If the connection has failed it will not return 0, it will block forever, or until the read timeout elapses if there is one. 0 means an orderly disconnect, not a cable pull for example. Mar 6, 2020 at 7:43
get sock opt may be somewhat useful, however, another way would to have a signal handler installed for SIGPIPE. Basically whenever you the socket connection breaks, the kernel will send a SIGPIPE signal to the process and then you can do the needful. But this still does not provide the solution for knowing the status of the connection. hope this helps.
You should try to use: getpeername function.
now when the connection is down you will get in errno: ENOTCONN - The socket is not connected. which means for you DOWN.
else (if no other failures) there the return code will 0 --> which means UP.
resources: man page: http://man7.org/linux/man-pages/man2/getpeername.2.html
-
3Nope. ENOTCONN means that the
connect
function has not been called on the socket passed to thegetpeername
function. Socket may be "connected", but it does not mean that the connection is up. Dec 17, 2015 at 18:17 -
-
2By "connected" I mean a socket on which
connect
has been successfully called. And by saying "up" I mean that the connection is not half-open. When the server acts only as listener, it can listen literally forever on a connected socket, which is not actually up (i.e. is half-open). This article explains half-open connections in detail: blog.stephencleary.com/2009/05/… Dec 26, 2015 at 21:17
On Windows you can query the precise state of any port on any network-adapter using: GetExtendedTcpTable
You can filter it to only those related to your process, etc and do as you wish periodically monitoring as needed. This is "an alternative" approach.
You could also duplicate the socket handle and set up an IOCP/Overlapped i/o wait on the socket and monitor it that way as well.
#include <sys/socket.h>
#include <poll.h>
...
int client = accept(sock_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
pollfd pfd = {client, POLLERR, 0}; // monitor errors occurring on client fd
...
while(true)
{
...
if(not check_connection(pfd, 5))
{
close(client);
close(sock[1]);
if(reconnect(HOST, PORT, reconnect_function))
printf("Reconnected.\n");
pfd = {client, POLLERR, 0};
}
...
}
...
bool check_connection(pollfd &pfd, int poll_timeout)
{
poll(&pfd, 1, poll_timeout);
return not (pfd.revents & POLLERR);
}
you can use SS_ISCONNECTED
macro in getsockopt()
function.
SS_ISCONNECTED
is define in socketvar.h
.
-
2
For BSD sockets I'd check out Beej's guide. When recv returns 0 you know the other side disconnected.
Now you might actually be asking, what is the easiest way to detect the other side disconnecting? One way of doing it is to have a thread always doing a recv. That thread will be able to instantly tell when the client disconnects.
-
9no it won't. The tcp stack can only detect that a socket is closed if (a) it receives a packet from the other side saying so, or (b) it times out waiting on an ack for a sent packet. In the case of a recv, if an intermediate router goes down or the remote host closes the socket abnormally (without sending a close), no packet will ever arrive to alert the socket stack that the recv is waiting on a shutdown connection. Nov 10, 2010 at 8:03