views:

465

answers:

1

hi all,

After making a tcp connection to a server, I close my linux application and Socket.close() is called.

Checking netstat -pant, I see the connection is in TIME_WAIT status.

This prevents me from making an immediate connection back to the server since I'm using the same port to connect from. Instead, I have to wait for the connection to timeout of the TIME_WAIT status before I can reconnect again.

I've played around -without luck- with the socket methods: set_so_timeout(), set_keepalive(), set_so_linger(), and set_reuseaddr() - exact spelling of the method may not be right in this post.

My question is HOW do I get the connection out of the TIME_WAIT status so I can instantly make a connection again?

Please let me know.

Thanks, jbu

+3  A: 

The best way to get the connection out of TIME_WAIT is (surprisingly) to wait :-)

That's how TCP/IP works. A session is identified by the tuple (sourceIP, sourcePort, destIP, destPort, protocol) and the reason why you can't re-use it is because there may be packets for it still out in the network somewhere.

TIME_WAIT state is generally twice the maximum packet lifetme and you should not be fiddling with it since that may cause packets to show up from the previous session (which will screw up your current session).

Ideally, you should connect from a different source port, then you will be able to open the session immediately.

Another thing you should watch out for is badly closed sessions. I've always subscribed to the guideline that the client should shut down the session (and shut it down cleanly). This minimizes the possiblity for long-lived half-closed sessions hanging around.

paxdiablo
Yes, the different port solves the problem and I will use that for now. However, the so_linger method description looks like it OUGHT to work if I want to use the same source port. I'm just not sure why it doesn't.
jbu
SO_LINGER is definitely not recommended. It's support is, at best, sporadic on non-BSD platforms.
paxdiablo
I don't think using another connection string is an elegant solution, there should be some way to force the TCP/IP to flush everything in the socket and close the connection.
Monis Iqbal
@Monis, the problem isn't something local that you can fix by flushing. There may still be packets floating around on the network. If you reuse the same 5-tuple and one of those old packets shows up, it will get in your way, causing, at best, retries and, at worst, data corruption (in the incredibly unlikely event the packet shows up with the correct sequence numbers).
paxdiablo
The only solution is to wait but wait how long? Please have a look at my recently posted question which might be related to this issue:http://stackoverflow.com/questions/3616704/jdbc-reconnect-problems-with-teradata-driver-using-spring-and-apache-datasource
Monis Iqbal