How to findout what ports are free using a linux shell script

Well it seems there is no one single command to do this. But what we can find out is already open ports. Using this we can find free ports by looping through port numbers.

Well the command is this:

$ lsof -iTCP:32000

The above command will search for the open port 32000 running the TCP protocol. If the port 32000 is open then there will be an output with the relevant details, else there will be no output. To use this information programatically we can do the following.

n=`lsof -iTCP:32000`

if [ "$n" != "" ]
then
    echo "Port is being used"
else
    echo "Port is free"
fi

The variable takes the output and if it is a empty string then the port is free else it is being used. (might be a better way of doing this check). All you have to do is to wrap this code around a loop to test the required port.

Tags: , , , ,

One Response to “How to findout what ports are free using a linux shell script”

  1. Zaf Says:

    nice, thanx, its helpful to me🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: