[cs631apue] Address in use

Jan Schaumann jschauma at stevens.edu
Tue Dec 11 21:46:59 EST 2012

wwang22 <wwang22 at stevens.edu> wrote:

> It happens a lot that once I run my program and occupy a port, and next  
> time I rerun it , the "Address in use" error always shows up.
> It seems that even though the program is end, the occupied port is not  
> released. So, I have to set a different port each time to test my  
> program.
> Is that normal? I don't know what's wrong. How should I fix the problem?

Look up the various states a TCP connection goes through in
https://www.rfc-editor.org/rfc/rfc793.txt Figure 6.

After a connection has been closed, the port ends up in TIME_WAIT
status.  (The output of netstat(1) should show this.)  That is, the
server waits for a little while to ensure the other side has in fact
received its connection termination confirmation.

If you wish to bind a socket on this port again, it will fail, as you
have observed.  To reuse the socket, you can set the SO_REUSEADDR option
on the socket via setsockopt(2).


More information about the cs631apue mailing list