When running any kind of server application like http or ftp server, or doing socket programming, it might so happen that a server program when recompiled/rerun fails to bind to a particular port number because that port number is already in use.
In such a case, you can either restart the system or close the port manually.
To close the port number manually first the process name/id has to be found out that is holding the port open and then use the kill command on that process.
Find pid with lsof - The lsof command can be used to find the pid and command name of the program or application that is currently using the port. Here is a quick example:
$ lsof -i :8888 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 8461 enlightened 11u IPv6 138527 0t0 UDP *:8888
In the above example it is seen that port 8888 is being held in use by the command java with pid 8461. Now kill the process by doing any of the following
$ kill 8461 or $ killall -9 8461 or $ killall -9 java
Find process/pid with netstat - The netstat command can also be used to find out which process is holding a certain port number
$ netstat -u -ap (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name udp 0 0 *:18347 *:* - udp 0 0 localhost:11211 *:* - udp 0 0 localhost:36254 localhost:36254 ESTABLISHED - udp 0 0 localhost:domain *:* - udp 0 0 *:ipp *:* - udp 0 0 *:42038 *:* - udp 0 0 *:17500 *:* 4090/dropbox udp 0 0 *:mdns *:* - udp 0 0 localhost:58797 localhost:7777 ESTABLISHED 9831/ncat udp 0 0 localhost:42724 localhost:domain ESTABLISHED - udp6 0 0 [::]:46282 [::]:* - udp6 0 0 [::]:mdns [::]:* - udp6 0 0 [::]:9999 [::]:* 11598/java
The port we want to close here is 9999. And netstat shows that the pid is "11598" and command name is "java". Over here we used the -u for udp port. If its a tcp port then the "-u" switch is not needed.
To make the search process easier, simply pipe the output of netstat to grep and look for the exact port number
$ sudo netstat -ap | grep :9050 tcp 0 0 localhost:9050 *:* LISTEN 1613/tor
Once the process id/name is found end it with the kill command.
$ kill 11598
Find pid with fuser - This is yet another command to find the pid/process holding a certain port number. The sytanx is as follows:
fuser -k -n protocol portno
$ fuser -k -n udp 7777 7777/udp: 11774
The above examples show how to find specific process and its pid that are using a given port number. Once you know the port number you can just kill that process and free the port.
Note that if the process was initially launched with root privileges then you would need root privileges to kill it as well.