Netstat command in Linux

The port number is a virtual concept in computer networking that provides a network identifier for a service or application. The number is a 16-bit integer from 0 to 65535 that combines with the IP address to create a network communication socket.

This article shows how to open a port in Linux and use Linux networking tools to list and test open ports.

Netstat command in Linux

The netstat command is a CLI tool for network statistics. It gives an overview of network activities and displays which ports are open or have established connections. The netstat tool is essential for discovering network problems.

This article shows 28 netstat commands for displaying port and internet statistics data on Linux.

Netstat command in Linux

  • Access to the terminal
  • Installed net-tools software package

Netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc.,

Examples of some practical netstat command :

The state of a port is either open, filtered, closed, or unfiltered. A port is said to be open if an application on the target machine is listening for connections/packets on that port.

In this article, we will explain four ways to check open ports and also will show you how to find which application is listening on what port in Linux.

Using Netstat Command

Netstat is a widely used tool for querying information about the Linux networking subsystem. You can use it to print all open ports like this:

$ sudo netstat -ltup

The flag -l tells netstat to print all listening sockets, -t shows all TCP connections, -u displays all UDP connections and -p enables printing of application/program name listening on the port.

Netstat command in Linux

Check Open Ports Using Netstat Command

To print numeric values rather than service names, add the -n flag.

$ sudo netstat -lntup

Netstat command in Linux

Show Numeric Values

You can also use grep command to find out which application is listening on a particular port, for example.

Netstat command in Linux

Find Port of Running Application

Alternatively, you can specify the port and find the application bound to, as shown.

Netstat command in Linux

Find Application Using a Port Number

Using ss Command

$ sudo ss -lntu

Netstat command in Linux

Find Open Ports Using ss Command

Using Nmap Command

Nmap is a powerful and popular network exploration tool and port scanner. To install nmap on your system, use your default package manager as shown.

$ sudo nmap -n -PN -sT -sU -p- localhost

Using lsof Command

The final tool we will cover for querying open ports is lsof command, which is used to list open files in Linux. Since everything is a file in Unix/Linux, an open file may be a stream or a network file.

To list all Internet and network files, use the -i option. Note that this command shows a mix of service names and numeric ports.

$ sudo lsof -i

Netstat command in Linux

List Open Network Files Using lsof Command

To find which application is listening on a particular port, run lsof in this form.

Netstat command in Linux

Find Application Using Port

Netstat command in Linux

Netstat is a command line utility that tells us about all the tcp/udp/unix socket connections on our system. It provides list of all connections that are currently established or are in waiting state. This tool is extremely useful in identifying the port numbers on which an application is working and we can also make sure if an application is working or not on the port it is supposed to work.

Netstat command also displays various other network related information such as routing tables, interface statistics, masquerade connections, multicast memberships etc.,

In this tutorial, we will learn about Netstat with examples.

(Recommended Read: Learn to use CURL command with examples )

Netstat with examples

To list out all the connections on a system, we can use ‘a’ option with netstat command,

$ netstat -a

This will produce all tcp, udp & unix connections from the system.

2- Checking all tcp or udp or unix socket connections

To list only the tcp connections our system, use ‘t’ options with netstat,

$ netstat -at

Similarly to list out only the udp connections on our system, we can use ‘u’ option with netstat,

$ netstat -au

To only list out Unix socket connections, we can use ‘x’ options,

$ netstat -ax

3- List process id/Process Name with

To get list of all connections along with PID or process name, we can use ‘p’ option & it can be used in combination with any other netstat option,

$ netstat -ap

4- List only port number & not the name

To speed up our output, we can use ‘n’ option as it will perform any reverse lookup & produce output with only numbers. Since no lookup is performed, our output will much faster.

$ netstat -an

5- Print only listening ports

To print only the listening ports , we will use ‘l’ option with netstat. It will not be used with ‘a’ as it prints all ports,

$ netstat -l

6- Print network stats

To print network statistics of each protocol like packet received or transmitted, we can use ‘s’ options with netstat,

$ netstat -s

7- Print interfaces stats

To display only the statistics on network interfaces, use ‘I’ option,

$ netstat -i

8-Display multicast group information

With option ‘g’ , we can print the multicast group information for IPV4 & IPV6,

$ netstat -g

9- Display the network routing information

To print the network routing information, use ‘r’ option,

$ netstat -r

10- Continuous output

To get continuous output of netstat, use ‘c’ option

$ netstat -c

11- Filtering a single port

To filter a single port connections, we can combine ‘grep’ command with netstat,

12- Count number of connections

To count the number of connections from port, we can further add ‘wc’ command with netstat & grep command,

This was our brief tutorial on Netstat with examples, hope it was informative enough. If you have any query or suggestion, please mention it in the comment box below.

If you think we have helped you or just want to support us, please consider these :-

Linux TechLab is thankful for your continued support.

A port is a logical entity that represents an endpoint of communication and is associated with a given process or service in an operating system. In previous articles, we explained how to find out the list of all open ports in Linux and how to check if remote ports are reachable using the Netcat command.

In this short guide, we will show different ways of finding the process/service listening on a particular port in Linux.

netstat (network statistics) command is used to display information concerning network connections, routing tables, interface stats, and beyond. It is available on all Unix-like operating systems including Linux and also on Windows OS.

Netstat command in Linux

Check Port Using netstat Command

In the above command, the flags.

  • l – tells netstat to only show listening sockets.
  • t – tells it to display tcp connections.
  • n – instructs it to show numerical addresses.
  • p – enables showing of the process ID and the process name.
  • grep -w – shows matching of exact string (:80).
:/>  Пропали ядра cpu где включить обратно

Note: The netstat command is deprecated and replaced by the modern ss command in Linux.

lsof command (List Open Files) is used to list all open files on a Linux system.

To install it on your system, type the command below.

To find the process/service listening on a particular port, type (specify the port).

Netstat command in Linux

Find Port Using lsof Command

Using fuser Command

You can find the process/service listening on a particular port by running the command below (specify the port).

Then find the process name using PID number with the ps command like so.

$ ps -p 2053 -o comm=
$ ps -p 2381 -o comm=

Netstat command in Linux

Find Port and Process ID in Linux

You can also check out these useful guides about processes in Linux.

That’s all! Do you know of any other ways of finding the process/service listening on a particular port in Linux, let us know via the comment form below.

Introduction to netstat command

netstat (network statistics) is a command-line utility in the Linux system to display network connections, routing tables, interface statistics, masquerade connections, and multicast memberships. netstat prints information about the Linux networking subsystem.

The output of the netstat command shows the information on active internet connections and active UNIX domain sockets.

Proto: The protocol used by the socket: TCP, UDP, raw.

Send-Q: The number of bytes that are not acknowledged by the remote host.

Local Address: It is the address and port number of the local end of the socket.

Foreign Address: It is the address and port number of the remote end of the socket.

State: The state of the socket.

  • ESTABLISHED: The socket has an established connection.
  • SYN_SENT: The socket is actively attempting to establish a connection.
  • SYN_RECV: A connection request has been received from the network.
  • FIN_WAIT1: The socket is closed, and the connection is shutting down.
  • FIN_WAIT2: A connection is closed, and the socket is waiting for a shutdown from the remote end.
  • TIME_WAIT: The socket is waiting after close to handle packets still in the network.
  • CLOSED: The socket is not being used.
  • CLOSE_WAIT: The remote end has shut down, waiting for the socket to close.
  • LAST_ACK: The remote end has shut down, and the socket is closed. (Waiting for acknowledgement)
  • LISTEN: The socket is listening for incoming connections. Such sockets are not shown in the output unless you use the option –listening (-l) or –all (-a).
  • CLOSING: Both sockets are shut down, but still all data has not been sent.
  • UNKNOWN: The state of the socket is unknown.

PID/Program name: The process id (PID) and process name of the process that owns the socket.

Timer: It contains information about networking timers.

Proto: The protocol used by the socket: UNIX.

RefCnt: The reference count (i.e. attached processes via this socket).

Flags: It displays the flags: SO_ACCEPTON (displayed as ACC), SO_WAITDATA (W) or SO_NOSPACE (N). ACC is used on unconnected sockets if their corresponding processes are waiting for a connection request.

Type: It contains the different types of socket access.

  • SOCK_DGRAM: It is used in Datagram (connectionless) mode.
  • SOCK_STREAM: It is a stream (connection) socket.
  • SOCK_RAW: The socket is used as a raw socket.
  • SOCK_RDM: It serves reliably delivered messages.
  • SOCK_SEQPACKET: It is a sequential packet socket.
  • SOCK_PACKET: Raw interface access socket.
  • FREE: The socket is not allocated.
  • LISTENING: The socket is listening for a connection request. Such sockets are not displayed in the output without -l or -a option.
  • CONNECTING: The socket is establishing a connection.
  • CONNECTED: The socket is connected.
  • DISCONNECTING: The socket is disconnecting.
  • (empty): The socket is not connected to another one.

I-Node: The inode of the socket.

PATH: The pathname to which the corresponding processes are attached to the socket.

Netstat command in Linux

Утилита netstat

netstat — стандартная утилита, входящая в состав операционной системы Windows 10. Она применяется для отображения сетевой информации, в том числе и позволяет посмотреть список открытых портов. Благодаря этому можно узнать состояние, тип порта, локальный и внешний адрес. Этот вариант приоритетный, поскольку не требует перехода на разные сайты и скачивания дополнительного программного обеспечения, а о принципах взаимодействия с этой командой читайте в статье по ссылке ниже. Там также описаны и доступные аргументы, которые рекомендуется использовать, чтобы показать только интересующие сведения.

Подробнее: Использование команды netstat для просмотра открытых портов

Netstat command in Linux

Порты нужны определенным программам и службам для входящих подключений, поэтому они обязательно отслеживаются стандартным межсетевым экраном. Любое разрешение на открытие порта сохраняется в соответствующем списке, который можно использовать для выполнения поставленной задачи, что происходит так:

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Некоторые программы и службы могут использовать все предлагаемые порты, поэтому в этом меню вы не найдете конкретной привязки к протоколу. Тогда придется обращаться за помощью к одному из следующих методов.

Онлайн-сервисы

Онлайн-сервисы — очень популярный вариант определения открытых портов, поскольку многие пользователи не желают задействовать консоль, чтобы получить какую-либо информацию. На просторах интернета находится огромное количество подходящих сайтов, которые бесплатно выводят список прослушиваемых портов, а о трех самых популярных из них мы предлагаем прочесть далее.

Подробнее: Сканирование портов онлайн

Netstat command in Linux

Способ 4

TCPView — небольшое программное обеспечение с графическим интерфейсом, которое было перекуплено компанией Microsoft и сейчас находится в свободном доступе на официальном сайте компании. По сути, это аналог рассмотренной выше команды, однако сведения показываются в более понятном виде, а наличие графического интерфейса является огромным плюсом TCPView.

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Способ 5

PortQry — дополнительная консольная утилита от компании Microsoft, которая позволяет просмотреть открытые порты. Мы рекомендуем пользоваться ее в том случае, если команда netstat и другие варианты вам не подходят, но нужно путем ввода всего одной команды просмотреть список абсолютно всех открытых портов.

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Веб-интерфейс маршрутизатора

Последний метод просмотра открытых портов в Windows 10 — переход к отдельному меню в интернет-центре роутера. Однако там можно увидеть только те порты, которые были вручную или по умолчанию открыты именно через настройки маршрутизатора, а осуществляется это на примере устройства от TP-Link так:

Выполните авторизацию в веб-интерфейсе маршрутизатора, следуя инструкциям из следующей статьи.

Подробнее: Вход в веб-интерфейс роутеров

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Если нужно открыть конкретный порт, который по каким-то причинам оказался закрыт, потребуется выполнить определенный алгоритм действий. Проще всего справиться с этой задачей, придерживаясь руководств по ссылкам далее.

Подробнее:
Открываем порты в брандмауэре Windows 10
Открываем порты на роутере

Еще статьи по данной теме

  • Используем команду netstat для просмотра открытых портов
  • Вопросы и ответы

Netstat command in Linux

Netstat — одна из встроенных команд операционной системы Windows. В ее функциональность входит отображение состояния сети со всеми требуемыми деталями. Пользователь задействует встроенный синтаксис, чтобы отфильтровать результаты или задать дополнительные действия для этой утилиты. В рамках сегодняшнего материала мы бы хотели рассказать о доступных методах просмотра открытых портов с помощью этого стандартного инструмента.

Портами называют натуральные числа, которые записываются в заголовках протоколов передачи данных (TCP, UDP и так далее). Они определяют процесс получения и передачи информации в рамках одного хоста и в большинстве случаев используются онлайн-программами для установки соединения. Просмотр открытых портов может понадобиться в случае определения работоспособности приложений или при стандартном мониторинге сети. Лучше всего с этим справится команда netstat, а ее активация доступна с применением разных аргументов.

:/>  Шаг за шагом: Редактирование меню загрузки Windows 7 и Windows 8

Отображение всех подключений и ожидающих портов

Самый простой аргумент, применяемый к утилите netstat, имеет обозначение -a, и отвечает за вывод сведений обо всех активных подключениях их портов, которые ожидают соединения. Такая информация доступна к просмотру без применения прав администратора и выводится на экран следующим образом:

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Мониторинг производится в режиме реального времени, поэтому не все результаты будут доступны к просмотру сразу. Придется подождать немного времени, чтобы все они могли прогрузиться. Во время этого не закрывайте консоль, если не хотите прервать процесс, ведь при повторном запуске команды все начнется заново.

Постраничное отображение открытых портов

К сожалению, приведенный выше вариант отображает не все необходимые данные об открытых портах, поскольку выводит он только те параметры, которые на текущий момент находятся в состоянии LISTENING. К тому же там не указывались уникальные идентификаторы процессов (PID), что тоже играет важную роль во время определенного мониторинга. Потому советуем обратить внимание немного на другие аргументы.

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Теперь хотелось бы поговорить про используемые аргументы и значение увиденных параметров. Давайте сначала затронем знакомые буквы синтаксиса:

Важно также уточнить и состояние портов, поскольку они могут являться открытыми, но на этот момент не использоваться или ожидать своего подключения. В колонке «Состояние» могут отображаться такие показатели:

Эти объяснения должны разобраться помочь не только с составлением запросов для netstat, но и без проблем разобраться с полученной информацией.

Запись результатов в текстовый файл

Иногда требуется сохранить готовые результаты мониторинга в текстовый файл, чтобы выполнить дальнейшие действия, ведь копировать информацию прямо из консоли не всегда удобно, да и займет это намного больше времени, нежели просто указать дополнительный аргумент при вводе команды.

Netstat command in Linux

Netstat command in Linux

Netstat command in Linux

Поиск по содержимому

В случае необходимости отображения только подключений с определенными параметрами или адресами лучше всего использовать дополнительную команду find, которая перед выводом сведений произведет фильтрацию данных, и это освободит вас от надобности вручную искать каждый соответствующий пункт. Тогда полная консольная команда приобретает следующий вид:

Netstat command in Linux

Netstat command in Linux

Выше вы узнали о методах определения открытых портов через встроенную команду netstat. После этого можете приступить к работе с программами или пробросу других портов в случае необходимости. К слову, этой теме посвящен отдельный материал на нашем сайте. Перейдите по указанным ниже ссылкам, чтобы ознакомиться с подробными инструкциями.

Команда netstat всегда показывает правильные результаты, однако если хотите убедиться в открытости порта другим путем, рекомендуем задействовать специальные онлайн-сервисы, позволяющие справиться с поставленной задачей.

How to Use netstat Command in Linux

The primary usage of netstat is without any parameters:

Netstat command in Linux

  • Proto – Protocol of the connection (TCP, UDP).
  • Recv-Q – Receive queue  of bytes received or ready to be received.
  • Send-Q – Send queue of bytes ready to be sent.
  • Local address – Address details and port of the local connection. An asterisk (*) in the host indicates that the server is listening and if a port is not yet established.
  • Foreign address– Address details and port of the remote end of the connection. An asterisk (*) appears if a port is not yet established.
  • State – State of the local socket, most commonly ESTABLISHED, LISTENING, CLOSED or blank.
  • Proto – Protocol used by the socket (always unix).
  • RefCnt – Reference count of the number of attached processes to this socket.
  • Flags – Usually ACC or blank.
  • Type – The socket type.
  • State – State of the socket, most often CONNECTED, LISTENING or blank.
  • I-Node – File system inode (index node) associated with this socket.
  • Path – System path to the socket.

For advanced usage, expand the netstat command with options:

Or list the options one by one:

The netstat options enable filtering of network information.

List All Ports and Connections

To list all ports and connections regardless of their state or protocol, use:

Netstat command in Linux

The output lists established connections along with servers which are open or listening.

List All TCP Ports

List all TCP ports by running:

Netstat command in Linux

List All UDP Ports

List all UDP ports with:

Netstat command in Linux

List Only Listening Ports

To return a list of only listening ports for all protocols, use:

Netstat command in Linux

List TCP Listening Ports

List all listening TCP ports with:

Netstat command in Linux

List UDP Listening Ports

Return only listening UDP ports by running:

Netstat command in Linux

List UNIX Listening Ports

To list UNIX listening ports, use:

Netstat command in Linux

Display Statistics by Protocol

Display statistics for all ports regardless of the protocol with:

Netstat command in Linux

Statistics are also filterable by protocol.

List Statistics for TCP Ports

List statistics for TCP ports only with:

Netstat command in Linux

List Statistics for UDP Ports

To list statistics for UDP ports only, use:

Netstat command in Linux

List Network Interface Transactions

To see transactions of MTU, receiving and transferring packets in the kernel interface table, use:

Netstat command in Linux

Display Extended Kernel Interface Table

Add the option -e to netstat -i to extend the details of the kernel interface table:

Netstat command in Linux

Display Masqueraded Connections

For displaying masqueraded connections, use:

Display PID

Display the PID/Program name related to a specific connection by adding the -p option to netstat. For example, to view the TCP connections with the PID/Program name listed, use:

Netstat command in Linux

Find Listening Programs

Find all listening programs with:

Netstat command in Linux

Display Kernel IP Routing Table

Display the kernel IP routing table with:

Netstat command in Linux

Display IPv4 and IPv6 Group Membership

Display group membership for IPv6/IPv4 with:

Netstat command in Linux

Print netstat Info Continuously

Add the -c option to the netstat command to print information every second:

For example, to print the kernel interface table continuously, run:

Netstat command in Linux

Find Unconfigured Address Families

List addresses without support on the system with:

The information is found at the end of the output:

Netstat command in Linux

Display Numerical Addresses, Host Addresses, Port Numbers, and User IDs

Display Numerical AddressesShow numerical addresses with:

Display Numerical Host AddressesTo show only host addresses as numerical, run:

Display Numerical Port NumbersShow only ports as numerical with:

Find a Process That Is Using a Particular Port

Make use of the grep command to filter the data from netstat. To find a process that is using a particular port number, run:

Netstat command in Linux

List All netstat Commands

There are many netstat options available. Access the list of all the available commands and a short description using:

Netstat command in Linux

For further reading, find out about the best network security tools.

Opening a Port in Linux

  • The UFW firewall on Ubuntu-based distributions.
  • firewalld on CentOS and other RHEL-based distributions.
  • The iptables utility for the systems without UFW and Firewalld.

Ubuntu and UFW Based Systems

UFW (Uncomplicated Firewall) for Ubuntu allows you to open a port with a single command:

The output confirms when you add IPv4 and IPv6 rules.

Netstat command in Linux

Alternatively, open the port used by a specific service without stating the port number:

Note: After you finish creating the rules, ensure UFW is active on your system by typing:

sudo ufw enable

CentOS and Other Systems with firewalld

The –permanent option ensures that the rules persist after the system reboot.

:/>  Текст для командной строки

Netstat command in Linux

Note: The –zone=public argument is necessary only in multi-zone system configurations. By default, firewalld assigns all interfaces to the public zone.

Linux Distributions without UFW or firewalld

While installing a full-fledged firewall is the recommended way of maintaining system security, some Linux distributions still use the legacy iptables solution. The iptables utility allows configuring rules to filter IP packets using the Linux kernel firewall.

The command creates an IPv4 rule. To create an IPv6 rule, use the ip6tables command:

The port number is specified with the –dport option. The -p flag allows you to define the protocol (tcp or udp). For example, to create an IPv4 rule for the TCP port 8080, type:

sudo iptables -A INPUT -p tcp –dport 8080 -j ACCEPT

Make iptables Rules Persist on Debian-Based Systems

The rules created using iptables do not persist after reboots.

1. Save the IPv4 rules you created:

2. Store any IPv6 rules in a separate file:

3. Install the iptables-persistent package:

sudo apt install iptables-persistent

This package automatically reloads the contents of the rules.v4 and rules.v6 files when the system restarts.

Netstat command in Linux

Make iptables Rules Persist on RHEL-Based Systems

RHEL-based systems store the iptables configuration in a different location.

1. Type the commands below to save the IPv4 and IPv6 rules, respectively:

2. Ensure the iptables-services package is installed:

sudo dnf install iptables-services

3. Start the service:

sudo systemctl start iptables

4. Enable the service:

sudo systemctl enable iptables

5. Save the iptables rule:

sudo service iptables save

Netstat command in Linux

6. Restart the service to enforce the rule:

sudo systemctl restart iptables

Listing Open Ports

Before opening a port on a system, check if the port you need is already open. The simplest way to do this is to pipe the output of the netstat command to the grep command.

The syntax above tells grep to look for a specific port number in the port list provided by netstat. For example, to check if port 8080 is available on the system, type:

If the port is closed, the command returns no output.

The -l option looks for the listening ports, -n provides numerical port values, while -t and -u stand for TCP and UDP, respectively.

Netstat command in Linux

What’s Next

View the listening ports with the netstat command:

Netstat command in Linux

The output above shows the port 8080 we opened previously.

List the open sockets with the ss command:

The port appears as part of the socket.

Netstat command in Linux

Test the port by specifying its number to the nmap command.

Netstat command in Linux

Test the Port with the Netcat Utility

The Netcat tool features the nc command that you can use to test an open port. To do so:

2. Leave the command running and open another terminal window.

3. In that terminal window, use a command such as telnet to query the local socket.

Netstat command in Linux

This article provided instructions on opening and testing a port in Linux. Opening a port can be helpful for various reasons, such as allowing incoming traffic to access a specific service or application on your system.

Different examples to use netstat command

In this tutorial, we will go through different practical examples of netstat commands to print network connections.

Syntax of netstat command

The general syntax of the netstat command is:

We will explore the different OPTIONS which we can use with netstat command in the next section.

Netstat command to display all connections

By default, netstat shows only connected connections/sockets. To view all of them in the output, you can use -a or -all option.

$ netstat –all

Netstat command in Linux

Netstat command to list all TCP ports connections

$ netstat -a –tcp

Netstat command in Linux

Netstat command to list all UDP ports connections

$ netstat -a –udp

Netstat command in Linux

Netstat command to display only listening connections

You can use -l option to get the list of only listening connections.

Netstat command in Linux

Display routing table with netstat command

$ netstat –route

Netstat command in Linux

Display available network interfaces with netstat command

To view the list of all network interfaces, you can execute the command below.

$ netstat –interfaces

Netstat command in Linux

Netstat command to display multicast group membership

$ netstat –groups

Netstat command in Linux

Display network statistics using netstat command

$ netstat –statistics

Netstat command in Linux

Display interface table for specific interface with netstat command

-e or –extend option displays the additional information in the output. You can use this option twice for maximum detail.

$ netstat -e

$ netstat –extend

Netstat command in Linux

As we can see, the additional columns are shown when using -e option.

Display PID/Program name with netstat command

-p or –program option shows PID and name of the program for sockets.

$ netstat -p

$ netstat –progress

Netstat command in Linux

Netstat command to print verbose output

You can use -v or –verbose option to print verbose or additional useful information. It also prints the information about unconfigured address families.

$ netstat -v

$ netstat –verbose

Print routing information from the route cache with netstat command

-C option prints the routing information from the route cache instead of FIB (Forwarding Information Base). The default is FIB.

$ netstat –cache

Netstat command in Linux

Show complete IP addresses with netstat command

$ netstat -W

$ netstat –wide

Netstat command in Linux

Netstat command to display timers

-o or –timers option shows the information related to networking timers.

$ netstat -o

$ netstat –timers

Netstat command in Linux

Display numeric values instead of names with netstat command

$ netstat -n

$ netstat –numeric

Netstat command in Linux

You can also use:

Display information continuously using netstat command

-c or –continuous option forces netstat to print the information every second continuously.

$ netstat –continuous

Use the command in your terminal to see the output.

Display Listening TCP and UDP connections

  • -t: Show TCP connections
  • -u: Show UDP connections
  • -p: Show the PID and name of the program to which each socket belongs
  • -l: Show only listening sockets

As you can see, the above command shows both IPv4 and IPv6 based connections. We can further filter it out, let’s check the same in next example from our cheat sheet.

Display only IPv6 connections with netstat command

We can use -6 argument with netstat command to only display only tcp6 and udp6 based connections. We will combine -6 with our above set of arguments to display listening TCP6 and UDP6 connections:

Display only IPv4 connections with netstat command

Similar to Ipv6, we can also force netstat to only print IPv4 connections using -4 argument. We will re-use our previous set of argument combining with -4 as shown below:

Further Reading

man page for netstat command

Conclusion

Now, we have come to the end of the tutorial. We hope we have helped you to learn netstat command. netstat is a helpful tool to view the information of network connections. If you still have any confusion, please let us know in the comment section.