【Linux】命令 - netstat

Posted by 西维蜀黍 on 2023-02-16, Last Modified on 2023-05-02
# List all ports:
$ netstat -a

# List all listening ports:
$ netstat -l

# Display PID and program names for a specific protocol:
$ netstat -p <protocol>

Listing Sockets by Type

The netstat -a command can provide more information than you need to see. If you only want or need to see the TCP sockets, you can use the -t (TCP) option to restrict the display to only show TCP sockets.

$ netstat -at

# -t (TCP, -u (UDP) and -x (UNIX)
# List listening TCP ports:
$ netstat -t
# List in-use UDP
$ netstat -u
# Liast all UNIX connection
$ netstat -x

# [combine] list listening TCP
$ netstat -lt

Listing Sockets by State

To see the sockets that are in the listening or waiting state, use the -l (listening) option.

netstat -l 

Network Statistics by Protocol

# -t (TCP), -u (UDP), or -x (UNIX) options
# check the statistics for the TCP protocol.
$ netstat -st

Showing Process Names and PIDs

It can be useful to see the process ID (PID) of the process using a socket, together with the name of that process. The -p (program) option does just that. Let’s see what the PIDs and process names are for the processes using a TCP socket that is in the listening state. We use sudo to make sure we receive all of the information that is available, including any information that would normally require root permissions.

netstat -p -at

Listing Numeric Addresses

Another step we can take to remove some ambiguity is to display the local and remote addresses as IP addresses instead of their resolved domain and hostnames. If we use the -n (numeric) option, the IPv4 addresses are shown in dotted-decimal format:

netstat -an

Displaying the Routing Table

The -r (route) option displays the kernel routing table.

$ netstat -r

# Print the routing table:
$ netstat -nr

Finding the Port Used by a Process

If we pipe the output of netstat through grep, we can search for a process by name and identify the port it is using. We use the -a (all), -n (numeric) and -p (program) options used previously, and search for “sshd.”

netstat -anp | grep "sshd"

List the Network Interfaces

The -i (interfaces) option will display a table of the network interfaces that netstat can discover.

netstat -i

Reference