-2

everyone, i want to know when my tcp connection will be finished. I mean the next: my prog is a client and it sends any messages to server, but it doesn't know when the server will close connection (send FIN flag). Its look like handshake, prog send first msg, then receive and send next msg on the same socket, then serv send FIN - flag, thats mean end of tcp session or end of handshake as you like. My target is to know when server say FIN, im using stream socket.

I tryed to use var flags from msdn doc int recv(SOCKET s ... int flags);. But now i think it isnt what im looking for...

int partresult = recv(*my_sock, RcvBytes, Size, 0);
Matthieu
  • 2,736
  • 4
  • 57
  • 87
Tesla69
  • 1
  • 1
  • 4
    `recv()` returns 0 if the connection has been closed gracefully by the peer (by sending a `FIN`), otherwise it returns `SOCKET_ERROR` (-1) on any error, including abnormal disconnects (ie, `WSAECONNRESET`, `WSAECONNABORTED`, etc). This is [documented on MSDN](https://learn.microsoft.com/en-us/windows/desktop/api/winsock/nf-winsock-recv), read it more carefully. – Remy Lebeau Jun 25 '19 at 20:21
  • 2
    `*mysock` = most probably wrong btw. – Michael Chourdakis Jun 25 '19 at 20:25
  • Possible duplicate of [Why is it impossible, without attempting I/O, to detect that TCP socket was gracefully closed by peer?](https://stackoverflow.com/questions/155243/why-is-it-impossible-without-attempting-i-o-to-detect-that-tcp-socket-was-grac) – Matthieu Jun 25 '19 at 20:34

1 Answers1

1

(I'm assuming you're referring to TCP as the FIN is used only in that context).

A call to recv() will tell you what you're looking for: it will return 0 when a FIN was received (i.e. the remote socket output was shutdown) (already stated by @RemyLebeau, and -1 in case of error).

I'm using this answer as an opportunity to warn you about not comparing its return value with the number of bytes expected to read, as TCP does not guarantee a single send() can be read with a single read(). So do not test if (partresult < RcvBytes) ....

Matthieu
  • 2,736
  • 4
  • 57
  • 87