How to use netstat on linux

Netstat – derived from the words network and statistics – is a command-line utility used by system administrators for analyzing network statistics. It displays a whole manner of statistics such as open ports and corresponding addresses on the host system, routing table, and masquerade connections.

In this article, we will walk you through how you can install the netstat command in different Linux distributions.

How to Install netstat Command in Linux

The package that contains netstat is called net-tools. On modern systems, the netstat utility comes pre-installed and there’s no need to install it.

On older systems, however, you are likely to bump into an error when you run the netstat command. Therefore, to install netstat on Linux distributions, run the command.

Once installed, run the command below to check the version of netstat installed.

How to Use netstat Command in Linux

You can invoke the netstat command on any of the Linux distributions to get different statistics on your network.

1. Viewing the Network Routing Table

You use the -r flag to show the network routing table to get something similar to the output below.

The -n option forces netstat to print addresses separated by dots instead of using symbolic network names. The option is useful for avoiding address lookups over a network.

2. Display Network Interface Statistics

Use the -i flag to get an output of statistics of a network interface that is configured. The -a option prints all present interfaces in the kernel.

3. Show Network Connections

The netstat command utility supports options that display active or passive sockets using the options -t , -n , and -a . The flags show RAW, UDP, TCP, or UNIX connection sockets. Adding the -a option, it will sow sockets ready for connection.

How to use netstat on linux

4. Show Network Services

To list services, their current state, and their corresponding ports, run the command.

How to use netstat on linux

In this article, we shed light on how you can install netstat command and how it is used to checking a wide array of network statistics. It’s also important to point out that netstat has been deprecated and instead ss utility has taken its place in displaying more refined network statistics.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Related Posts

How to use netstat on linux

How to use netstat on linux

How to use netstat on linux

How to use netstat on linux

How to use netstat on linux

How to use netstat on linux

2 thoughts on “How to Install netstat Command in Linux”

I should point out that it is actually the most modern system that is likely to be missing netstat since ss is a newer replacement.

Arch Linux install is incorrect. “netstat-nat” is a different package that does not install the same.

Got something to say? Join the discussion. Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

To check the listening ports and applications on Linux:

  1. Open a terminal application i.e. shell prompt.
  2. Run any one of the following command on Linux to see open ports:
    sudo lsof -i -P -n | grep LISTEN
    sudo netstat -tulpn | grep LISTEN
    sudo ss -tulpn | grep LISTEN
    sudo lsof -i:22 ## see a specific port such as 22 ##
    sudo nmap -sTU -O IP-address-Here
  3. For the latest version of Linux use the ss command. For example, ss -tulw

Let us see commands and its output in details.

Option #1: lsof command

The syntax is:
$ sudo lsof -i -P -n
$ sudo lsof -i -P -n | grep LISTEN
$ doas lsof -i -P -n | grep LISTEN ### [OpenBSD] ###
Sample outputs:

Fig.01: Check the listening ports and applications with lsof command

  • sshd is the name of the application.
  • 10.86.128.138 is the IP address to which sshd application bind to (LISTEN)
  • 22 is the TCP port that is being used (LISTEN)
  • 85379 is the process ID of the sshd process

Option #2: netstat command

You can check the listening ports and applications with netstat as follows.

Linux netstat syntax

How to use netstat on linux

Run netstat command along with grep command to filter out port in LISTEN state:
$ netstat -tulpn | grep LISTEN
The netstat command deprecated for some time on Linux. Therefore, you need to use the ss command as follows:
sudo ss -tulw
sudo ss -tulwn
sudo ss -tulwn | grep LISTEN

Where, ss command options are as follows:

  • -t : Show only TCP sockets on Linux
  • -u : Display only UDP sockets on Linux
  • -l : Show listening sockets. For example, TCP port 22 is opened by SSHD server.
  • -p : List process name that opened sockets
  • -n : Don’t resolve service names i.e. don’t use DNS

FreeBSD/MacOS X netstat syntax

$ netstat -anp tcp | grep LISTEN
$ netstat -anp udp | grep LISTEN

OpenBSD netstat syntax

$ netstat -na -f inet | grep LISTEN
$ netstat -nat | grep LISTEN

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:

Option #3: nmap command

The syntax is:
$ sudo nmap -sT -O localhost
$ sudo nmap -sU -O 192.168.2.13 ##[ list open UDP ports ]##
$ sudo nmap -sT -O 192.168.2.13 ##[ list open TCP ports ]##
Sample outputs:

How to use netstat on linux

Fig.02: Determines which ports are listening for TCP connections using nmap

A note about Windows users

You can check port usage from Windows operating system using following command:
netstat -bano | more
netstat -bano | grep LISTENING
netstat -bano | findstr /R /C:”[LISTEING]”

Conclusion

This page explained command to determining if a port is in use on Linux or Unix-like server. For more information see the nmap command and lsof command page online here or by typing the man command as follows:
man lsof
man ss
man netstat
man nmap

When troubleshooting network connectivity or application-specific issues, one of the first things to check should be what ports are actually in use on your system and which application is listening on a specific port.

This article explains how to use the netstat , ss and lsof commands to find out which services are listening on which ports. The instructions are applicable for all Linux and Unix-based operating systems like macOS.

What is Listening Port #

Network port is identified by its number, the associated IP address, and type of the communication protocol, such as TCP or UDP.

Listening port is a network port on which an application or process listens on, acting as a communication endpoint.

Each listening port can be open or closed (filtered) using a firewall. In general terms, an open port is a network port that accepts incoming packets from remote locations.

You can’t have two services listening to the same port on the same IP address.

For example, if you are running an Apache web server that listens on ports 80 and 443 and you try to install Nginx , the later will fail to start because the HTTP and HTTPS ports are already in use.

Check Listening Ports with netstat #

netstat is a command-line tool that can provide information about network connections.

To list all TCP or UDP ports that are being listened on, including the services using the ports and the socket status use the following command:

The options used in this command have the following meaning:

  • -t – Show TCP ports.
  • -u – Show UDP ports.
  • -n – Show numerical addresses instead of resolving hosts.
  • -l – Show only listening ports.
  • -p – Show the PID and name of the listener’s process. This information is shown only if you run the command as root or sudo user.

The output will look something like this:

The important columns in our case are:

  • Proto – The protocol used by the socket.
  • Local Address – The IP Address and port number on which the process listen to.
  • PID/Program name – The PID and the name of the process.

If you want to filter the results, use the grep command . For example, to find what process listens on TCP port 22 you would type:

The output shows that on this machine port 22 is used by the SSH server:

If the output is empty it means that nothing is listening on the port.

You can also filter the list based on criteria, for example, PID, protocol, state, and so on.

netstat is obsolete and replaced with ss and ip , but still it is of the most used commands to check network connections.

Check Listening Ports with ss #

ss is the new netstat . It lacks some of the netstat features, but exposes more TCP states and it is slightly faster. The command options are mostly the same, so the transition from netstat to ss is not difficult.

To get a list of all listening ports with ss you would type:

The output is almost the same as the one reported by netstat :

Check Listening Ports with lsof #

lsof is a powerful command-line utility that provides information about files opened by processes.

In Linux, everything is a file. You can think of a socket as a file that writes to the network.

To get a list of all listening TCP ports with lsof type:

The options used are as follows:

  • -n – Do not convert port numbers to port names.
  • -p – Do not resolve hostnames, show numerical addresses.
  • -iTCP -sTCP:LISTEN – Show only network files with TCP state LISTEN.

Most of the output columns names are self-explanatory:

  • COMMAND , PID , USER – The name, the pid and the user running the program associated with the port.
  • NAME – The port number.

To find what process is listening on a particular port, for example, port 3306 you would use:

The output shows that MySQL server uses port 3306 :

For more information, visit the lsof man page and read about all other powerful options of this tool.

Conclusion #

We have shown you several commands that you can use to check what ports are in use on your system, and how to find what process listens on a specific port.

If you have any questions or remarks, please leave a comment below.

report this ad

netstat is very useful tool which provides a lot of information about the network of operating system. netstat command can list ip addreass, route, port, connections etc. More detailed information about the netstat command can be found in the following tutorial.

We can use netstat -l options in order to list all listening ports. This will list both TCP and UDP ports with IPv4 and IPv6 . But also Unix domain sockets will be printed in the end of the list after TCP and UDP ports.

How to use netstat on linux

List All Listening Ports

TCP is reliable protocol which provides non data loss. Applications generally prefers and uses TCP protocol for network connections and data transfer. We can use -t option in order to only list TCP ports.

How to use netstat on linux

List Listening TCP Ports

We have also have the ability to only list UDP ports. We will use -u option in order to only list UDP ports.

How to use netstat on linux

List Listening UDP Ports

We can also list only established connections by removing -l option which is used in previous examples. -l was used to list only listening ports.

How to use netstat on linux

List Established Connections

Now the most funny part. If we are running netstat in a busy server or system we will get a lot of output. In this situations we should filter printed list. We will use grep command where detailed information can be get from following tutorial.

Filter SSH Port

Filter HTTP Port

Filter RDP Port

Filter Telnet Port

If we need to filter multiple ports in a single command we should use grep or logic. In this example we will filter both ssh and telnet ports in single command.

Filter Multiple Ports In Single Command

A port scan sends client requests to a server port addresses on a host for finding an active port. The design and operation of the Internet is based on TCP/IP. A port can have some behavior like below:

  1. Open or Accepted: The host sent a reply indicating that a service is listening on the port.
  2. Closed or Denied or Not Listening: The host sent a reply indicating that connections will be denied to the port.
  3. Filtered, Dropped or Blocked: There was no reply from the host.

This is often used by administrators to verify security policies of their networks and can be used by an attacker to identify running services on a host with the view to compromise it.

To find all open/listening ports in your Kali Linux machine, we’ll use Netstat tool which is an open source tool and is already installed in Kali Linux OS. Netstat prints information about the Linux networking subsystem.

According to Wikipedia – Netstat (network statistics) is a command-line network utility tool that displays network connections for the Transmission Control Protocol (both incoming and outgoing), routing tables, and a number of network interface (network interface controller or software-defined network interface) and network protocol statistics.

It is available on Unix-like operating systems including macOS, Linux, Solaris, and BSD, and is available on Windows NT-based operating systems including Windows XP, Windows Vista, Windows 7, Windows 8 and Windows 10.

To find open ports, type the below command in your machine terminal.

Command: sudo netstat -plntu

How to use netstat on linux

Where, -p = display PID/Program name for sockets,
-l = display listening server sockets,
-n = don’t resolve names,
-t = tcp ports,
-u = udp ports

As you can see in above screenshot, the port numbers 5432, 5433, 80 and 68 ports are open in which Port 80 is associated with Apache Service and Port 68 is associated with Dhclient Service, and rest all other ports are linked with Postgres service.

In another article, we explained computer ports and what they’re used for. Other than that, what can we do with port information? Since all traffic in and out of the computer goes through ports, we can check on them to see what they’re doing. Maybe the port isn’t listening for traffic? Maybe something is using a port that shouldn’t be?

We’re going to use the Windows command netstat to see our listening ports and PID (Process ID). We’re also going to see what we can do with that information.

How to use netstat on linux

What Is Netstat?

The netstat command is a combination of the words ‘network’ and ‘statistics’. The netstat command works in all versions of Windows from Windows XP right up to Windows 10. It’s also used in other operating systems (OS) like Unix and Linux, but we’ll stick to Windows here.

Netstat can provide us with:

  • The name of the protocol the port is using (TCP or UDP).
  • The local IP address and name of the computer and the port number being used.
  • The IP address and port number to which we’re connecting.
  • The state of a TCP connection. For details on what these states are, read the Event Processing section of RFC 793.

Using Netstat To See Listening Ports & PID

  • Use the key combination Win Key + X. In the menu that opens, select Command Prompt.

How to use netstat on linux

  • Enter the command
    netstat -a -n -o

    . The parameters for netstat are preceded with a hyphen, not a forward slash like many other commands. The -a tells it to show us all active connections and the ports on which the computer is listening.

  • View the results and take note of the addresses, port numbers, state, and PID. Let’s say we want to know what’s using port 63240. Note that its PID is 8552 and it’s connecting to the IP address 172.217.12.138 on port 443.

How to use netstat on linux

What’s Using That Port?

  • Open Task Manager. That’s most easily done by using the key combination Ctrl + Shift + Esc.

How to use netstat on linux

  • Click on the Details tab. To make this easier to find, click on the PID column header to sort the PIDs numerically.

How to use netstat on linux

  • Scroll down to PID 8552 and see what process it is. In this case, it’s googledrivesync.exe. But is it really? Sometimes viruses can make themselves look like legitimate processes.

How to use netstat on linux

  • In a web browser, go to ipinfo.io. Enter the IP address 172.217.12.138. As we can see, the IP address is registered to Google. So this googledrivesync.exe is a legitimate one.

How to use netstat on linux

How To Get Port, PID, & Process Name In PowerShell

PowerShell is Microsoft’s newer way to use a command-line interface with Windows. We say newer, but it’s been around for several versions. You should learn PowerShell even if you’re a home user.

Most Windows commands also work in PowerShell, plus we can combine them with PowerShell’s cmdlets – pronounced command-lets. Joe at Winteltools.com provides the script for this method.

  • Open Notepad and enter the following code:

How to use netstat on linux

  • Save the file as get-NetstatProcessName.ps1. Make sure to note where it’s being saved. It’s important to change the Save as type: to All Files (*.*) or it will get saved as get-NetstatProcessName.ps1.txt and it won’t work for us.

How to use netstat on linux

  • Open PowerShell and navigate to the location in which the script was saved. In this case, it’s
    cd C:\Scripts

    . Hit Enter to run the command.

  • Run the script using dot-sourcing to make it work. That means use ./ before the name of the file. The command will be
    ./get-NetstatProcessName.ps1
  • Now we can see all the traditional netstat info plus the process name. No need to open Task Manager anymore.

How to use netstat on linux

Go Get Them

We’ve covered two ways to use the netstat command to see listening ports. It can be used either in the old Command Prompt or within a PowerShell script. With the information it can give us, we’ve looked at how it can help us figure out what our computer is doing.

If you thought netstat is a great utility, take a look at some other Windows TCP/IP utilities like tracert, ipconfig, and nslookup. Or use Resource Monitor to get a better look into hidden website and Internet connections. There is a lot you can do to see exactly what your computer is doing.

Have you used netstat to solve a problem? Please tell us what you did. Any questions about how to use netstat? Please ask us in the comments below.

Guy has been published online and in print newspapers, nominated for writing awards, and cited in scholarly papers due to his ability to speak tech to anyone, but still prefers analog watches. Read Guy’s Full Bio

Because the port configuration can cause a security risk, it’s critical to know which ports are open.

How to use netstat on linux

This article explains how to check for open ports using netstat, lsof and nmap commands to find out which services are listening on which ports.

Table of Contents

When troubleshooting network connectivity or application-specific issues, one of the first things to check should be what ports are actually in use on your system and which application is listening on a specific port.

Network port is identified by its number, the associated IP address, and type of the communication protocol, such as TCP or UDP. Above all, open port is a network port on which an application or process listens on, acting as a communication endpoint.

Each listening port can be open or closed (filtered) using a firewall. In general terms, an open port is a network port that accepts incoming packets from remote locations.

Check for Open Ports with netstat

netstat (network statistics) is a command line tool for monitoring network connections both incoming and outgoing as well as viewing routing tables, interface statistics etc. This tool is very important and much useful for Linux network administrators as well as system administrators to monitor and troubleshoot their network-related problems and determine network traffic performance.

To list all TCP or UDP ports that are being listened on, including the services using the ports and the socket status use the following command:

The options used in this command have the following meaning:

  • -t : Show TCP ports.
  • -u : Show UDP ports.
  • -l : Show only listening ports.
  • -n : Show numerical addresses instead of resolving hosts.
  • -p : Show the PID and name of the listener’s process. This information is shown only if you run the command as root or sudo user.

The important columns in our case are:

  • Proto – The protocol used by the socket.
  • Local Address – The IP Address and port number on which the process listen to.
  • PID/Program name – The PID and the name of the process.

In addition, if you want to filter the results, use the grep command . For example, to find what process listens on TCP port 22 you would type:

If the output is empty it means that nothing is listening on the port.

For more about netstat command in Linux, consult its manual page.

Check for Open Ports with lsof

lsof meaning ‘LiSt Open Files’ is used to find out which files are open by which process. In Linux, everything is a file. You can think of a socket as a file that writes to the network.

To get a list of all listening TCP ports with lsof type:

The options used are as follows:

  • -n : Do not convert port numbers to port names.
  • -P : Do not resolve hostnames, show numerical addresses.
  • -iTCP -sTCP:LISTEN : Show only network files with TCP state LISTEN.

To find what process is listening on a particular port, for example, port 3306 you would use:

The output shows that MySQL server uses port 3306.

For more about lsof command in Linux, consult its manual page.

Check for Open Ports with nmap

nmap , or Network Mapper, is an open source Linux command line tool for network exploration and security auditing. With nmap, server administrators can quickly reveal hosts and services, search for security issues, and scan for open ports.

nmap commands can be used to check a single port or a series of ports are open.

Here’s how to scan port 80 on the target system:

Scan ports 1 through 200 on the target system:

Scan (Fast) the most common ports:

Bottom Line

In conclusion, checking which ports are open and what information can be obtained from the services accepting connections on those ports gives you the information that you need to lock down your server. For example, any extraneous information leaked out of your machine can be used by a malicious user to try to exploit known vulnerabilities or develop new ones. The less they can figure out, the better.

netstat -s prints out a lot of very detailed protocol statistics like number of TCP reset messages received or number of ICMP “echo request” messages sent or number of packets dropped because of a missing route.

When in Linux netstat is considered deprecated at nowadays, then is there an alternative?

Statistics provided by ss -s are superficial compared to the ones provided by netstat .

3 Answers 3

NETSTAT is considered deprecated at nowadays and others programs included in the net-tools like arp, ifconfig, iptunnel, nameif, netstat , and route.

The functionality provided by several of these utilities has been reproduced and improved in the new iproute2 suite, primarily by using its new ip command.

Examples for deprecated commands and their replacements:

  • arp → ip n ( ip neighbor )
  • ifconfig → ip a ( ip addr ), ip link , ip -s ( ip -stats )
  • iptunnel → ip tunnel
  • iwconfig → iw
  • nameif → ip link , ifrename
  • netstat → ss , ip route (for netstat -r ), ip -s link (for netstat -i ), ip maddr (for netstat -g )

The netstat command reads various /proc files to gather information. However this approach falls weak when there are lots of connections to display. This makes it slower. The ss command gets its information directly from kernel space. The options used with the ss commands are very similar to netstat making it an easy replacement.

Statistics provided by ss are superficial but it is considered the better alternative to netstat

Examples

See note in netstat manpage:

netstat has indeed been deprecated by many distributions, though it’s really much of the “net-tools” package (including ifconfig , route and arp ) that has been deprecated in favour of the “iproute2” package. iproute2 has evolved along with the latest Linux networking features, and the traditional utilities have not.

The iproute2 equivalent that you want is the little known nstat , this provides the netstat -s counters, albeit in a slightly different form:

raw counter names from /proc are used, each prefixed with its class (“Udp”, “Tcp”, “TcpExt” etc)

netstat’s long (and possibly localised) descriptions are not available

zero-value counters omitted by default

using consistent columnar output with the name and value in the first and second columns

third column shows the average over a configurable time window if you have started a background nstat ( -d daemon mode), or 0.0 if not

e.g. nstat prints “UdpInDatagrams NNN” not “Udp: InDatagrams”, and not the verbose netstat version of “Udp: NNN packets received”.

nstat also assumes you want incremental rather than absolute numbers, so the closest equivalent to netstat -s is /sbin/nstat -asz where the options are -a use absolute counters, -s don’t keep history file, -z don’t omit zero-value counters.

ss takes over the “socket” parts of netstat , but not its complete function as you have found out. ( ss is actually better than netstat in many cases, two specific ones are the ability to use filter expressions and the optional capability to use the tcp_diag and inet_diag Linux kernel modules to access kernel socket data more directly than via /proc .)

Should you need to confirm the mapping for descriptive names, the net-tools source is the definitive reference: http://sourcecodebrowser.com/net-tools/1.60/statistics_8c_source.html

Doug Vitale provides a useful guide for finding the iproute2 equivalents of the older commands (it is unmaintained and slightly incomplete, it omits any reference to nstat which has been part of the iproute2 package since at least 2004 kernel 2.6.x time).

net-tools lives on however, and you should be able to find a package for your distribution (or compile it yourself).

TIME_WAIT is a socket state during TCP connection termination. It represents waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request.

Netstat is a handy command to check the network connections in Linux system. We can use netstat command to check which connection is in the time_wait state.

Today we will dive into time_wait in Linux.

  • When and where time_wait happens?
  • What is the impact of time_wait Tcp connections?
  • How to reduce the time_wait timer in Linux?
  • Example of time_wait in Linux

When and where time_wait happens?

Time_wait could happen on the client-side or server-side. It depends on which side terminates the tcp session. From the above chart, A is the active closer and B is the passive closer.

When A closes the connection, it will send a FIN packet to B. After A gets the Ack and FIN back from B, tcp connection will change to time_wait on A-side. Time_wait happens on the active closer side.

What is the impact of time_wait Tcp connections?

Time_wait state is a normal part of a TCP socket’s life cycle. Smaller numbers of TIME WAIT sockets are normal. If there are a lot of time_wait sockets, it will need some time to exit.

If our application needs to create new sockets at this time, it will fail because we don’t have enough ports now.

How to reduce the time_wait timer in Linux?

The RFC defines the time spent in TIME WAIT state as “2 times MSL (Maximum Segment Lifetime)”. But the Linux kernel’s implementation of TCP is hard-coded with a TIME WAIT counter of 60 seconds.

So there is no way to reduce this timer. But in some operating systems, we can reuse these ports by configuring some kernel parameters.

Example of time_wait in netstat command

This is a normal tcp connection on our Cassandra server. We can use netstat -anpl to check the connection status in Linux.

tcp 0 115 10.253.113.116:37640 10.241.94.101:7000 ESTABLISHED 31945/java

Now let’s shutdown Cassandra on the server-side, we can see that the TCP connection became Time_wait.

tcp 0 0 10.253.113.116:37640 10.241.94.101:7000 TIME_WAIT –

If we see time_wait connections, that means something wrong with the application. It terminates the connections. We should check what happens from the application side.

Lets start with the basics. The netstat command is quite useful for checking connections to your machine. If we wanted to see ALL of the connections (which i really recommend you don’t do unless you’re trying to debug something and then you should probably pipe it to a file) we could use the “netstat -a” command.

Using netstat -a will give you something sort of like this (this is a segment of my server):

As you can see it does name resolving for us and all that good stuff. Sometimes very hand but that’s not what this is about. We want to get some solid numbers so we can take a broader perspective. To do this we can use the following command: netstat -an | wc -l

This will show us a count of all connections that we presently have to our machine. But we can take this one step further even. Lets say you only wanted to see traffic comming across port 80 (standard http). We can grep our netstat then count it like so: netstat -an | grep :80 | wc -l

Finally, lets take a look at the big picture in a category form. It is often extremely useful to see what those connections are doing, especially when you think you might just have tons of open connections that are idle and are trying to tweak your settings. It’s been known to happen where you have a really busy web server for instance, and maybe it’s running a lot of database connections to the same box, then stopping. That often causes things like the TIME_WAIT to pile up and a large number for any of these may be an indication that you need to adjust your tcp timeout settings.

So there you have it. A quick way to return counts on your connections in your linux environment. (Note the netstat command is standard on most operating systems, including windows, but you may need to use some other way to count your results)

Occasionally, when using netstat you may only care about ports that you are listening on. This is especially important if you are running a server that isn’t behind a firewall because it helps you determine what you may be vulnerable to that you aren’t aware of. using the netstat -l provides us with an excellent way to view this information.

Another very common thing and powerful tool that netstat has built in is to show you network statistics in an overview fashion. If you’re just trying to get a good idea about packet statistics then the netstat -s command may be what you’re looking for. Here is some sample output. Keep in mind that netstat -s will show statistics broken down by protocol, so the fewer protocol stacks you are running the more compacted this summary will be.

Another extremely useful tool for server administrators who are trying to track down processes that have run amuck is the netstat -p command. This returns the PID of the process that has the connection. It’s also quite useful if you’ve got someone abusing a PID and you need to find out what IP it is so that you can get in touch with that individual or to block connections from that IP in the future. Here’s some sample output from netstat -p.

Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.

How to use netstat on linux Get application security done the right way! Detect, Protect, Monitor, Accelerate, and more…

netstat is a command-line network tool that is a handy troubleshooting command. Its cross-platform utility means you can use it on Linux, macOS, or Windows.

netstat can be very handy in the following.

  • Display incoming and outgoing network connections
  • Display routing tables
  • Display number of network interfaces
  • Display network protocol statistics

Let’s get it started…

Show all connections

To start with netstat, let’s see the command that displays all connections.

Type the above command and hit enter. You will see all the active connections from different states as shown below.

You will see a header with Proto, Local Address, Foreign Address, and State. Let’s see brief info about them.

  • Proto – defined the protocol type (TCP, UDP, etc. ) of the socket.
  • Local Address – displays your computer IP address and port, local end of the socket.
  • Foreign Address – displays remote computer that your computer is connected to, the remote end of the socket.
  • State – defines the state of the socket (LISTENING, ESTABLISHED, CLOSE_WAIT, TIME_WAIT).

We can filter the connections in different ways. Let’s see them.

Show only established connection

We have seen the state in the connection information. You can use below syntax to view all established connections from/to your Windows server.

Note: to view LISTEN, CLOSE_WAIT, TIME_WAIT you can just use as follows.

To see the connections that are in LISTENING state change ESTABLISHED keyword in the previous command to LISTENING. You will get the information about connections that are in the listening state as follows.

Similarly, run the following command to see all the connections that are in CLOSE_WAIT state.

Finally, use the TIME_WAIT flag to get information about all the connections that are in TIME_WAIT state.

Show PID used by port number

Every connection is a process internally. And every process has an ID, and its called PID. We can see the PID of every socket connection using the following command.

The above command displays all the connections with PID. Let’s run the command and see how we get the result.

We got an extra column called PID. And its the process identifier.

A very handy when you have to find out which PID is using the particular port number.

You can see the following info if you use the above command.

Show statistics of all protocols

Useful when you have to find out for any received header error, received address error, discarded packet, etc. It will list out statistics from IPv4, IPv6, ICMPv4, ICMPv6, TCP, UDP, etc.

You will see the statistics of all protocols as shown below.

To find out any errors quickly you can use syntax.

The above command filters all the errors from statistics of all protocols.

Show routing information

To display Route Table, you can use the below syntax. The following syntax will also list all interfaces.

If you use the above command, then you see the info about routing as shown below.

Show Interface Statistics

To view the status of all interface, you can use the following syntax. This will display Received & Sent details.

Show Fully Qualified Domain Name of foreign address (remote host)

If you are tracking some issues and would like to know FQDN of the remote host, then you can use the following syntax.

If you run the above command, then you will see a similar result as follows.

Note: you can combine findstr syntax to show precise results like below.

The above command will filter the connections and displays only established connections. Let’s see an example.

We can filter the connections using the domain with the following command.

Specify the domain in the command and you will see the filtered connections as follows.

I hope this helps you get familiar with netstat command usage on Windows. If you are interested in learning Windows administration then I would suggest checking out this course.

Okay, this is creeping me out – I see about 1500-2500 of these:

That number is changing rapidly.

I do have a pretty tight iptables config so I have no idea what can cause this. any ideas?

Edit: Output of ‘netstat -anp’:

6 Answers 6

EDIT: tcp_fin_timeout DOES NOT control TIME_WAIT duration, it is hardcoded at 60s

As mentioned by others, having some connections in TIME_WAIT is a normal part of the TCP connection. You can see the interval by examining /proc/sys/net/ipv4/tcp_fin_timeout :

And change it by modifying that value:

Or permanently by adding it to /etc/sysctl.conf

Also, if you don’t use the RPC service or NFS, you can just turn it off:

And turn it off completely

TIME_WAIT is normal. It’s a state after a socket has closed, used by the kernel to keep track of packets which may have got lost and turned up late to the party. A high number of TIME_WAIT connections is a symptom of getting lots of short lived connections, not nothing to worry about.

It isn’t important. All that signifies is that you’re opening and closing a lot of Sun RCP TCP connections (1500-2500 of them every 2-4 minutes). The TIME_WAIT state is what a socket goes into when it closes, to prevent messages from arriving for the wrong applications like they might if the socket were reused too quickly, and for a couple of other useful purposes. Don’t worry about it.

(Unless, of course, you aren’t actually running anything that should be processing that many RCP operations. Then, worry.)

Something on your system is doing a lot of RPC (Remote Procedure Calls) within your system (notice both source and destination is localhost). That’s often seen for lockd for NFS mounts, but you might also see it for other RPC calls like rpc.statd or rpc.spray.

You could try using “lsof -i” to see who has those sockets open and see what’s doing it. It’s probably harmless.

tcp_fin_timeout does NOT control TIME_WAIT delay. You can see this by using ss or netstat with -o to see the countdown timers:

even with tcp_fin_timeout set to 3 the countdown for TIME_WAIT still starts at 60. However if you have net.ipv4.tcp_tw_reuse set to 1 ( echo 1 > /proc/sys/net/ipv4/tcp_tw_reuse ) then the kernel can reuse sockets in TIME_WAIT if it determines there won’t be any possible conflicts in TCP segment numbering.

I had the same problem too. I cost me several hours to find out what is going on. In my case, the reason for this was that netstat tries to lookup the hostname corresponding to the IP (I assume it’s using the gethostbyaddr API). I was using an embedded Linux installation which had no /etc/nsswitch.conf. To my surprise, the problem only exists when you are actually doing a netstat -a (found this out by running portmap in verbose and debug mode).

Now what happened was the following: Per default, the lookup functions also try to contact the ypbind daemon (Sun Yellow Pages, also known as NIS) to query for a hostname. To query this service, the portmapper portmap has to be contacted to get the port for this service. Now the portmapper in my case got contacted via TCP. The portmapper then tells the libc function that no such service exists and the TCP connection gets closed. As we know, closed TCP connections enter a TIME_WAIT state for some time. So netstat catches this connection when listing and this new line with a new IP issues a new request that generates a new connection in TIME_WAIT state and so on.

In this article I will share examples to check port status and open a port in Linux. This article was written while using CentOS 8, so it is safe to say that it also fully covers CentOS/RHEL 7/8, Fedora, Oracle Enterprise Linux and generally the whole Red Hat family of operating systems and possibly Novell’s SLES and OpenSUSE.

Before we jump into the examples to open a port in Linux, we must understand the requirement clearly. The very basic question which comes to my mind

  1. Do you need to open a port for a service? Such as a custom port 5555 for apache service?
  2. Do you mean the port is already listening but blocked by firewall so you want to open a port in firewall?
  3. Open a port for custom temporary task such as transfer and receive files using this port and then close the port.

We will cover all these scenarios in this article

Check port status

To check the list of existing ports which are open we will use nmap to check port status:

Currently we see only two ports are open on my CentOS 8 node.

Check list of listening ports

We will use netstat to list the TCP ports which are in listening state. The total number of ports are higher compared to the nmap output.

Open a port for some service

If this is your requirement then you are looking for the wrong question. Basically it is other way round i.e. a service will open a port. For example when you start SSHD service, by default it will start port 22 and not the other way round i.e. if you open port 22, it will not automatically start SSHD service.

Let us observe this in example, we know that port 22 is open on my CentOS 8 node. If I stop the sshd service

You can see that port 22 is not open anymore.

You must use respective service’s configuration file to change the default port. Once done you can restart the service and that should automatically open the respective port on your Linux node.

This covers the first scenario.

firewalld open port

It is also possible that your ports are disabled in firewall. If your port is not listed in nmap then it is most likely blocked by firewall.

We will use firewalld to open a port as this is the most used interface today in RHEL/CentOS 7 and 8. Determine which zone the system’s network interfaces are in. In the following example, the eth0 and eth1 interface is in the ‘public’ zone:

To permanently firewalld open port in a zone use the –add-port option. The example below permanently opens TCP port 1234 in the ‘public‘ zone. Note that permanent changes do not take effect until the firewalld service is reloaded.

Once firewalld open port, next use netstat to check port status:

We still don’t see port 1234 here. This is because currently port 1234 is not bind to any service . So our port is OPEN but NOT LISTENING. As soon as a request or service tries to use port 1234, we will get this in LISTEN state.

Use nc or ncat to open a port in Linux

Let us verify this theory Use nc or ncat to open a port in Linux nc or ncat is delivered as part of nmap-ncat rpm in RHEL/CentOS which you can install using yum or dnf. Use –listen with –port to open a port using nc command. In the below example we open port 1234

Open another terminal of this server and check port status

As you see port 1234 is listening for both IPv4 and IPv6. To only use IPv4 use -4 with the above command

Next on another terminal you can check port status for port 1234

Use nc or ncat to open a port and transfer files

We can also use nc to transfer file from one host to another host. Here I will transfer my ” inputfile ” from centos-8 to rhel-8 On the client we will open a random port, here we will use 9899. I have enabled verbose so you can see more details on the screen

Next to start the transfer, use the below command

If you face any issues you can check the firewall between your server and client. It is possible that the respective port is blocked and you must use firewalld open port

Lastly I hope the steps from the article to open a port and check port status on Linux was helpful. So, let me know your suggestions and feedback using the comment section.

Related Posts

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

3 thoughts on “Easy steps to open a port in Linux RHEL/CentOS 7/8”

A very thorough and helpful post. I was trying to allow ssh on a secondary port and could not get it to work using the usual advice (w/CentOS8.)
The recommendation you provided to add the port using the firewall-cmd was the missing ingredient:

Thanks for this!

Hi
I did below steps and reloaded firewall but still when I do netstat -ntlp port 1234 not showing open

I did explained this part in the article

We still don’t see port 1234 here. This is because currently port 1234 is not bind to any service. So our port is OPEN but NOT LISTENING. As soon as a request or service tries to use port 1234, we will get this in LISTEN state.