HOWTO lists the ports a system is listening on

From LinuxReviews
Jump to navigationJump to search

Knowing what ports the various services running on a machine are listening on can be quite useful and it's real easy to find out. All you have to do is to run netstat with the -l option or lsof with the -i option.

Getting a Quick overview of ports the machine is listening on with netstat[edit]

Netstat will by default try to lookup the reverse IP PTR records so you may also want to add -n to prevent that; it's just faster. Adding protocols like --tcp or --udp limit's it's output to those ports.

Thus, to find out all ports something is accepting tcp connections on you can run:

netstat --tcp -l -n


or


sudo lsof -i :53 to find out what local DNS resolver you have, if any, using lsof


And you can, of course, just run netstat -l -n to get a list which includes all protocols. This list does include domains sockets and that list is long so piping it to less with netstat -l -n|less is a good idea.

netstat is a part of a package called net-tools and it's typically installed by default on all systems.

Netstat has the advantage of very quickly providing an overview of the ports the machine is listening on. This is useful if you start a service which should listen on say port 80 and you wonder if it actually started listening or not.

What netstat does not give you is information regarding what is listening on a port.

Getting detailed information showing what applications and daemons are listening to ports[edit]

Listening-ports.jpg

lsof, described in the manual page as "list open files", can show network connections as well as files. This includes ports programs are listening on. The trick is to use the -i option.

Using lsof has one clear advantage over netstat: It will not only tell you what ports something is listening on, it will also tell you what program, what PID it has and what user it is running as.

Kemonomimi rabbit.svg
Note: lsof will only work as root. Any user can run netstat -l -n and get a list of ports. lsof -i -n -P will produce absolutely nothing if you run it as a regular user.

lsof will, like netstat, try to do reverse look-ups so adding -n for no lookups is advisable. Note that you have to use -i -n, NOT -in when you add -n.

lsof will also translate port numbers to service descriptions using /etc/services by default which means that port 80 will be shown as http, 443 will be listed as https and so on. The handy option -P prevents this behavior and tell you the actual port number.

Running lsof -i -n -P will list all the open network connections including established ones. You can simply grep to get the ports programs are listening on:

lsof -i -n -P | grep LISTEN