lsof


Bash: Close a range of open sockets by killing the PIDs that are holding them open

Sometimes you want to use a specific port number but some other process(es) is using it. To get the control of the port you need to terminate all other processes and free it.
To find out which process(es) you need to kill, use lsof -i :port. It will return a list of each command and PID that is using the specific port. After that kill those PID using kill -s 9.

The following script will accept a range of ports to free, and for each it will try to kill all processes that are holding them blocked.

low=12345;
high=12350;
for i in `seq $low $high`; do
  lsof -i :$i | tail -n +2 | awk '{system("kill -s 9 " $2)}';
done

Using tail -n +2 we skip the first line of the input which would be the header information.
The system method will invoke a new sh shell and execute the command in it.
Using kill -s 9 we signal the processes that they have to terminate immediately.