Take the 2-minute tour ×

I have implemented a forward proxy in linux which listens on few ports. Whenever a connection happens it puts into outer world. My setup looks as follows:

Outerworld<----->Proxy(Listens on Port A)<------->Browser(Configured with proxy set toPort A)

However, I am not sure when to close the connection between proxy-outer world and proxy-browser. I was under impression that if I see a packet with data size 0 (recv()) then it is end of communication from client side. Once I get "recv()=0", I do "close()" with outer world. Is this the right way to do? Or should I do shutdown()? Also, I think sometimes browser sends a a "FIN" with data packet and I fail to catch it. I sometimes see connection from browser on a socket which was never closed. (Linux reuses the same fd numbers. That is one of the reason, I believe I am missing socket closure.)

Where could I be going wrong.


share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

For a generic TCP forwarder, shutdown is the right thing to use. When you read an EOF from one side, stop reading that side and shutdown the writing on the other side. Then you can keep reading and writing the other direction until it also gives you an EOF, and then you close both.

share|improve this answer
But can browser send FIN with datalen more than 0. If that can happen then how to detect connection closure. –  agent.smith Aug 17 '12 at 3:39
You'll do a read, get the final data, write it to the other socket, do another read, get EOF, and do the shutdown. –  Alan Curry Aug 17 '12 at 4:12
Hey Alan, So just to clarify: "world(www_sockfd)<-->(client_sockfd)Proxy(server_sockfd)<-->(browser_sockfd)Bro‌​wser" Now if I recv() returns 0 on server_sockfd then I need to do shutdown on writing(client_sockfd). Once, I recv(), 0 bytes on client_sockfd then I close() on both client_sockfd and server_sockfd. Is this right? –  agent.smith Aug 17 '12 at 23:00
add comment

Your Answer


