0

I'm writing a C function to check if a socket connection from client is available. I use 'recv' function with MSG_PEEK not to alter the input buffer.

However, when the socket connection is closed by client, 'recv' is supposed to return -1, but it doesn't. After client closed, 'recv' in the function below returns 0 all the times.

char is_avail(int connection) {
  char buffer;

  int result = recv(connection,&buffer,1,MSG_PEEK);
  if (result<0)
    return 0;
  else
    return 1;
}

Any reason to this matter? and also I want to combine MSG_PEEK with MSG_WAITALL. I tried:

recv(connection,&buffer,1,MSG_PEEK|MSG_WAITALL);

but it doesn't take effect.

jondinham
  • 8,271
  • 17
  • 80
  • 137
  • *check if a socket connection from client is available* You're calling `recv` on a socket on which you called `listen` ? – cnicutar Aug 21 '12 at 07:42
  • Don't use `MSG_WAITALL` as it will block until it can fulfill your request. So it will block until there is data to read (or peek in your case), which in theory can be forever. – Some programmer dude Aug 21 '12 at 08:03
  • @JoachimPileborg Actually, recv does that per default already, unless the socket is set to 'non-blocking'. MSG_WAITALL is pointless in this case anyway, since it'd wait until 1 byte can be read...which is equal to the amount of bytes it's waiting for without MSG_WAITALL. – ATaylor Aug 21 '12 at 08:15
  • 1
    MSG_PEEK and general isAvailable checking from sockets is a bad idea. It has earned a place in Winsock programmers Lame list - because of its inherently unreliable nature. Dont use PEEK, just copy all data to your own buffers immediately. – kert Sep 01 '14 at 07:57
  • @kert quite old comment.. however, I am currently considering to change a protocol from fixed size buffers to dynamically sized messages and would be interested in any pro/cons of MSG_PEEK, do you know any ressources on the topic? – 463035818_is_not_an_ai Jun 22 '17 at 11:55

1 Answers1

5

recv does NOT return -1 when the socket is closed properly, but rather '0'.

0 -> graceful closing of the socket

-1-> An actual error occurred

> 0-> Data has been read.

ATaylor
  • 2,598
  • 2
  • 17
  • 25
  • 3
    @PaulDinh No, it doesn't. If there is no data to be read, it does not return at all. It blocks, until there IS data to be read. An exception to this: When you set up the socket to be non-blocking. In this case, the recv will return -1, if there is no data. The only time recv will return '0', is when the connection is actually closed. – ATaylor Aug 21 '12 at 08:16
  • my socket is non-blocking, i setup it with fcntl(socket,F_SETFL,O_NONBLOCK);, but 'recv' returns 0, is it still the exception – jondinham Aug 21 '12 at 08:19
  • 1
    @PaulDinh Have you tried checking with Wireshark, if the connection has been established correctly and not severed again in the meantime? The socket is connected, right? Because '0' indicates 'closed connection', after all. – ATaylor Aug 21 '12 at 08:41