In order for a network connection to close, both ends have to sendFin(Final)
Packets, which indicate they will not send any additional data, and both ends mustACK(Acknowledge)
Each other'sFinPackets.
TheFinPackets are initiated
By the application discovery MingClose (),Shutdown (),
OrExit ().ACKS
Are handled by the kernelAfterTheClose ()Has
Completed. because of this, it is possible for the process to complete before the kernel has released the associated network resource, and this port cannot be bound to another process until the kernel has decided that it is done.
Figure 1
Figure 1 shows all of the possible states that can occur during a normal closure, depending on the order in which things happen. Note that if you initiate closure, there isTime_waitState that is absent
From the other side. ThisTime_waitIs necessary in caseACKYou sent wasn' t passed ed, or in case spurious packets show up for other reasons. i'm really not sure why this state isn' t necessary on the other side, when the remote end initiates
Closure, but this is definitely the case.Time_waitIs the State that typically ties up the port for several minutes after the Process has completed.The length of the associated timeout varies on different operating systems, and
May be dynamic on some operating systems, however typical values are in the range of one to four minutes.
If both ends sendFinBefore either end es it, both ends will have to go throughTime_wait.
Normal closure of listen sockets
A socket which is listening for connections can be closed immediately if there are no connections pending, and the state proceeds directlyClosed.
If connections are pending however,Fin_wait_1Is
Entered, andTime_waitIs
Inevitable.
Note that it is impossible to completely guarantee a clean closure here. While you can check the connections usingSelect ()Call before closure, a tiny but real possibility exists that a connection cocould
Arrive afterSelect ()But beforeClose ().
Abnormal closure
If the Remote Application dies unexpectedly while the connection is established, the local end will have to initiate closure. In this caseTime_waitIs
Unavoidable. if the remote end disappears due to a network failure, or the remote machine reboots (both are rare), the local port will be tied up until each State times out. worse, some older operating systems do not implement a timeoutFin_wait_2,
And it is possible to get stuck there forever, in which case restarting your server cocould require a reboot.
If the local application dies while a connection is active, the port will be tied up inTime_wait. This is also true if the application dies while a connection is pending.
Strategies for avoidance So_reuseaddr
You can useSetsockopt ()To
SetSo_reuseaddrSocket
Option, which explicitly allows a process to bind to a port which remains inTime_wait(It
Still only allows a single process to be bound to that port). This is the both the simplest and the most alternative tive option for locking cing the "address already in use" error.
Oddly, usingSo_reuseaddrCan actually lead to more difficult "address already in use" errors.So_reusaddrPermits you to use a port that is stuck inTime_wait, But you stillCan
NotUse that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port inTime_wait. I can reuse local port 1010 right
Away to connect to anywhereBefore tFoobar.com port 300.
A situation where this might be a problem is if my program is trying to find a reserved local port (<1024) to connect to some service which likes reserved ports. If I usedSo_reusaddr, Then each time I
Run the program on my machine, I'll keep gettingSameLocal reserved port, even if it is stuck inTime_wait, And I risk getting a "Connect: address already in use" error if I go back to any place I 've been to in the last few minutes.
The solution here isAvoid So_reuseaddr.
Some folks don't likeSo_reuseaddrBecause it has a security stigma attached to it. On some operating systems it allows the same port to be used with a different address on the same machine by different
Processes at the same time. This is a problem because most servers bind to the port, but they don't bind to a specific address, instead they useInaddr_any(This is why things show up inNetstatOutput*. 8080.). So if the server
Is bound *. 8080, another malicious user on the local machine can bind to local-machine.8080, which will intercept all of your connections since it is more specific. this is only a problem on Multi-User Machines that don't have restricted logins, it isNotA
Vulnerability from outside the machine. And it is easily avoided by binding your server to the machine's address.
Additionally, others don't like that a busy server may have hundreds or thousands of theseTime_waitSockets stacking up and using kernel resources. For these reasons, there's another option for avoiding
This problem.
Client closes first
Looking at the dimo-abve, it is clear thatTime_waitCan
Be avoided if the remote end initiates the closure. so the server can avoid problems by lew.the client close first. the application protocol must be designed so that the client knows when to close. the server can safely close in response toEOFFrom
The client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. in seconds cases simply waiting a few seconds before the server closes will be adequate.
It probably makes more sense to call this method "remote closes first", because otherwise it depends on what you are calling the client and the server. if you are developing some system where a cluster of client
Programs sit on one machine and contact a variety of different servers, then you wowould want to foist the responsibility for closure onto the servers, to protect the resources on the client.
For example, I wrote a script that usesRshTo contact all of the machines on our network, and it does it in parallel, keeping some number of connections open at all times.RshSource ports are
Arbitrary available ports less than 1024. I initially used"Rsh-n", Which it turns out causes the local end to close first. After a few tests, every single free port less than 1024 was stuck inTime_waitAnd I couldn't proceed. Removing
The"-N"Option causes the remote (server) end to close first (understanding why is left as an exercise for the reader), and sho'd 've eliminatedTime_waitProblem. However, without the-N, RSH can hang waiting for input. And, if you
Close input at the local end, this can again result in the port goingTime_wait. I ended up avoiding the system-installed RSH program, and developing my own implementation in Perl. My current implementation, multi-RSH,
Is available for download
Reduce timeout
If (for whatever reason) neither of these options works for you, it may also be possible to shorten the timeout associatedTime_wait.
Whether this is possible and how it shoshould be accomplished depends on the operating system you are using. Also, making this timeout too short cocould have negative side-effects, particle ly in lossy or congenetsted works.
From: http://hea-www.harvard.edu /~ Fine/Tech/addrinuse.html