When I write the service-side program, after the end of the server-side program run, start the program again, the BIND function will return address already in using this error, prompting me that the port is already occupied.
Use # NETSTAT–APN | grep [port] command or Lsof-i:[port] command to see the port occupancy, you can find that the previously terminated server-side program process is still listening on the port. The kill command kills and then starts to run normally. Later in this article found the reason http://www.ibm.com/developerworks/cn/linux/l-sockpit/.
You can use an bind
API function to bind an address (an interface and a port) to a socket endpoint. You can use this function in server settings to limit the interfaces that may come with the connection. You can also use this function in client settings to limit the interfaces that should be used for connections that should be made available. The bind
most common usage is to associate the port number and server, and use a wildcard address ( INADDR_ANY
), which allows any interface to be used for incoming connections.
bind
The common problem is trying to bind a port that is already in use. The trap is that there may not be an active socket, but it is still forbidden to bind the port ( bind
returned EADDRINUSE
), which is caused by the TCP socket state TIME_WAIT
. The status is retained for approximately 2-4 minutes after the socket is closed. TIME_WAIT
after the status exits, the socket is deleted and the address can be re-bound without problems.
Waiting for TIME_WAIT
the end can be annoying, especially if you are developing a socket server, you need to stop the server to make some changes, and then restart. Fortunately, there are ways to avoid the TIME_WAIT
state. You can apply SO_REUSEADDR
socket options to sockets so that ports can be reused immediately.
Adding the following code before the BIND function solves the problem.
1 int 1 ; 2 if sizeof 0 )3{ 4 perror ("Server setsockopt failed " ); 5 return 1 ; 6 }
Linux socket programming address already in use problem