Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a certain port is open and unused?

Tags:

I want to install webserver-apache on a Linux platform which uses port no.80 but I am not sure whether is port is open or not, and is being used by some other application or not.

  1. Output of grep 80 /etc/services is:
http  80/tcp  www www-http   #World Wide web Http
http  80/udp  www www-http   #Hypertext transfer protocol
  1. netstat -an | grep 80 | more:

It gives some IP's one of which is

IP:80 TIME_WAIT

Could you please help and tell how can i find out if port 80 is open and unused so that I can start installation.

like image 873
Richa Avatar asked Dec 22 '12 09:12

Richa


People also ask

How do I check for unused ports?

You can use "netstat" to check whether a port is available or not. Use the netstat -anp | find "port number" command to find whether a port is occupied by an another process or not. If it is occupied by an another process, it will show the process id of that process.

What port is unused?

Port 1024 through 49151 are not restricted, although apps that use them may have "reserved" the port via IANA registration. Port 0 is a pseudo port where an app can bind to it and the OS will search and define one within the acceptable dynamic range (49152 through 65535).


2 Answers

sudo netstat -anp | grep ':80 '

That should give you pid & name of the process that holds port 80

like image 65
tink Avatar answered Sep 28 '22 22:09

tink


This can be achieved using the nc command as follows:

# nc -z IP PORT

It will return TRUE if the port is already in use, or FALSE is it (i.e, available not listening currently).

I don't recommend lsof or netstat method as it first try to scan all running PIDs to get all bounded ports:

# time lsof -i:8888
real    0m1.194s
user    0m0.137s
sys 0m1.056s```

# time nc -z 127.0.0.1 8888
real    0m0.014s
user    0m0.011s
sys 0m0.004s

Here 8888 is an unused port. The nc command is ~85 times faster in the above example.

Eg 1:

$ nc -z 127.0.0.1 80 && echo "IN USE" || echo "FREE"
IN USE

$ nc -z 127.0.0.1 81 && echo "IN USE" || echo "FREE"
FREE

Eg 2:

If you are trying with a remote IP, it is better to add a timeout to auto-exit if it is not accepting connection for the specified time.

$ nc -w 2 -z 216.58.196.174 81

Its Google's IP which is not used, so it will timeout after trying for 2 seconds.

like image 35
Seff Avatar answered Sep 29 '22 00:09

Seff