c - Is there a way to detect that TCP socket has been closed by the remote peer, without reading from it? -


first, little background explain motivation: i'm working on simple select()-based tcp "mirror proxy", allows 2 firewalled clients talk each other indirectly. both clients connect server, , both clients connected, tcp bytes sent server client forwarded client b, , vice-versa.

this more or less works, 1 slight gotcha: if client connects server , starts sending data before client b has connected, server doesn't have anywhere put data. don't want buffer in ram, since end using lot of ram; , don't want drop data either, client b might need it. go third option, not select()-for-read-ready on client a's socket until client b has connected. way client blocks until ready go.

that more or less works too, side effect of not selecting-for-read-ready on client a's socket if client decides close tcp connection server, server doesn't notified fact -- @ least, not until client b comes along , server selects-for-read-ready on client a's socket, reads pending data, , gets socket-closed notification (i.e. recv() returning 0).

i'd prefer if server had way of knowing (in timely manner) when client closed tcp connection. there way know this? polling acceptable in case (e.g. have select() wake once minute , call issocketstillconnected(sock) on sockets, if such function existed).

if want check if socket closed instead of data, can add msg_peek flag on recv() see if data arrived or if 0 or error.

/* handle readable on */ if (b_is_not_connected) {     char c;     ssize_t x = recv(a_sock, &c, 1, msg_peek);     if (x > 0) {         /* ...have data, leave in socket buffer until b connects */     } else if (x == 0) {         /* ...handle fin */     } else {         /* ...handle errors */     } } 

even if closes after sending data, proxy wants forward data b first before forwarding fin b, there no point in knowing has sent fin on connection sooner after having read data has sent.

a tcp connection isn't considered closed until after both sides send fin. however, if has forcibly shutdown endpoint, not know until after attempt send data on it, , receive epipe (assuming have suppressed sigpipe).


after reading mirror proxy application bit more, since firewall traversal application, seems need small control protocol allow verify these peers allowed talk each other. if have control protocol, have many solutions available you, 1 advocate have 1 of connections describe server, , other connection describe client. then, can reset connection client if there no server present take connection. can let servers wait client connection timeout. server should not initiate data, , if without connected client, can reset server connection. eliminates issue of buffering data dead connection.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -