1

In Windows platform I can check if a socket is connected by this code:

bool isConnected(int socket)
{
    int err;
    int len = sizeof (err);
    getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&err, &len);
    return err == 0;
}

In OS X this function always returns true. What is the official way to do it?

mh taqia
  • 3,506
  • 1
  • 24
  • 35

3 Answers3

2

This function works for both Windows and Mac platforms:

bool isConnected(int socket)
{
    int err;
    #ifdef __APPLE__
    uint32_t len;
    #elif _Windows
    int len;
    #endif
    sockaddr_in addr;
    len = sizeof (addr);
    err = getpeername(socket, (sockaddr*)&addr, &len);
    return err == 0;
}
ott--
  • 5,642
  • 4
  • 24
  • 27
mh taqia
  • 3,506
  • 1
  • 24
  • 35
  • This is not a good solution. `getpeername()` can returned cached info after a disconnect before the socket handle is closed. – Remy Lebeau Aug 10 '13 at 22:17
1

The only way I know to determine if a blocking socket is connected is to perform an actual send/recv operation and check the result for error. On Windows, a non-blocking socket can also issue asynchronous notifications on socket activity, like FD_CLOSE for disconnects.

The one place SOL_ERROR comes in handy is for a non-blocking connect() call. After select() reports the connect operation is finished, SOL_ERROR can be used to determine whether connect() was successful or why it failed.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

This - if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) is close enough to winsock's isConnected.

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main() {
  register int s;
  register int bytes;
  struct sockaddr_in sa;
  char buffer[BUFSIZ+1];

  if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
    perror("socket");
    return 1;
  }

  bzero(&sa, sizeof sa);

  sa.sin_family = AF_INET;
  sa.sin_port = htons(13);
  sa.sin_addr.s_addr = htonl((((((192 << 8) | 43) << 8) | 244) << 8) | 18);
  if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) {
    perror("connect");
    close(s);
    return 2;
  }

  while ((bytes = read(s, buffer, BUFSIZ)) > 0)
    write(1, buffer, bytes);

  close(s);
  return 0;
}
Software_Designer
  • 8,490
  • 3
  • 24
  • 28