How to Unbind a Port in Unix


Image

Have you ever tried to use a proxy or another networking program only to find that the port your needed was already being used? The following Bash script will kill any processes that are currently using your port.

#!/bin/sh

sudo lsof -i :$1 | awk '{if (NR!=1) {print $2}}' | uniq | xargs kill -9

Lets break it down step by step.

lsof outputs information about files that are currently open. The -i flag displays a list of files whose internet address matches the supplied value. A semicolon is used to denote a port number, and $1 is the first parameter passed into our script. The sudo command is required to gain access to the necessary network information.

The data that lsof outputs is very verbose, and we only require the process ids of the offending programs. This is where awk comes in.

awk is a versatile program that allows us to easily parse information. The code within the single quotes represents a command that will be executed on every line that is inputed into awk.

{if (NR!=1) {print $2}} is a command that says “print a row from the second column if the line number of this row is not equal to 1 (so we don’t print the column header).” This will generate a list of process ids. Passing this information into uniq will remove any duplicates.

xargs will take each of the individual process ids and pass them to the kill program one by one. The -9 flag is the signal number that will be sent to the process in question. In this instance 9 represents the KILL signal, which will force the process to end, thus freeing the required port.


comments powered by Disqus