Linux에서 netstat를 사용하는 방법

Linux netstat명령은 네트워크 연결, 사용중인 포트 및이를 사용하는 프로세스에 대한 정보를 제공합니다. 사용 방법을 알아보십시오.

포트, 프로세스 및 프로토콜

네트워크 소켓은 연결되거나 연결 대기 중일 수 있습니다. 연결은 TCP (Transport Control Protocol) 또는 사용자 데이터 그램 프로토콜 UDP와 같은 네트워킹 프로토콜을 사용합니다. 인터넷 프로토콜 주소와 네트워크 포트를 사용하여 연결을 설정합니다.

소켓 이라는 단어   는 리드 또는 케이블에 대한 물리적 연결 지점의 이미지를 떠올리게 할 수 있지만이 컨텍스트에서 소켓은 네트워크 데이터 연결의 한쪽 끝을 처리하는 데 사용되는 소프트웨어 구조입니다.

소켓에는 두 가지 주요 상태가 있습니다. 즉, 연결되어 지속적인 네트워크 통신을 촉진하거나 들어오는 연결이 연결 되기를 기다리고 있습니다. 소켓이 원격 장치에서 연결을 설정하는 중간에있을 때의 상태와 같은 다른 상태가 있지만 일시적인 상태를 제쳐두면 소켓이 연결 중이거나 대기 중 (종종 수신 이라고 함 ) 으로 생각할 수 있습니다 .

청취 소켓을 서버 라고하고 청취 소켓 과의 연결을 요청하는 소켓을 클라이언트 라고합니다 . 이러한 이름은 하드웨어 또는 컴퓨터 역할과 관련이 없습니다. 단순히 연결의 각 끝에서 각 소켓의 역할을 정의합니다.

netstat명령을 사용하면 연결된 소켓과 수신 대기중인 소켓을 찾을 수 있습니다. 즉, 사용중인 포트와 사용중인 프로세스를 알려줍니다. 네트워크 인터페이스 및 멀티 캐스트 연결에 대한 라우팅 테이블과 통계를 보여줄 수 있습니다.

의 기능은 netstatip 및 ss와 같은 다른 Linux 유틸리티에서 시간이 지남에 따라 복제되었습니다. 모든 네트워크 분석 명령의이 할아버지를 아는 것은 여전히 ​​가치가 있습니다. 모든 Linux 및 Unix와 유사한 운영 체제, 심지어 Windows 및 Mac에서도 사용할 수 있기 때문입니다.

사용 방법은 다음과 같습니다. 예제 명령이 포함되어 있습니다.

모든 소켓 나열

-a(모두) 옵션 차종은 netstat모두에게 연결되고 대기 소켓을 보여줍니다. 이 명령은 긴 목록을 생성 할 수 있으므로 less.

netstat -a | 적게

목록에는 TCP (IP), TCP6 (IPv6) 및 UDP 소켓이 포함됩니다.

터미널 창을 둘러싸 기 때문에 무슨 일이 일어나고 있는지보기가 조금 어렵습니다. 다음은 해당 목록의 몇 가지 섹션입니다.

활성 인터넷 연결 (서버 및 설정 됨) Proto Recv-Q Send-Q 로컬 주소 외부 주소 상태 tcp 00 localhost : domain 0.0.0.0:* LISTEN tcp 00 0.0.0.0:ssh 0.0.0.0:* LISTEN tcp 00 localhost : ipp 0.0.0.0:* LISTEN tcp 00 localhost : smtp 0.0.0.0:* LISTEN tcp6 0 0 [::] : ssh [::] : * LISTEN tcp6 0 0 ip6-localhost : ipp [::] : * 듣기. . . 활성 UNIX 도메인 소켓 (서버 및 설정 됨) Proto RefCnt 플래그 유형 상태 I- 노드 경로 unix 24 [] DGRAM 12831 / run / systemd / journal / dev-log unix 2 [ACC] STREAM LISTENING 24747 @ / tmp / dbus-zH6clYmvw8 unix 2 [] DGRAM 26372 / run / user / 1000 / systemd / notify unix 2 [] DGRAM 23382 / run / user / 121 / systemd / notify unix 2 [ACC] SEQPACKET LISTENING 12839 / run / udev / control

"활성 인터넷"섹션에는 원격 연결 요청을 수신하는 연결된 외부 연결 및 로컬 소켓이 나열됩니다. 즉, 외부 장치에 설정되거나 설정 될 네트워크 연결을 나열합니다.

"UNIX 도메인"섹션에는 연결된 내부 연결 및 수신 대기중인 연결이 나열됩니다. 즉, 운영 체제의 여러 응용 프로그램, 프로세스 및 요소간에 컴퓨터 내에서 설정된 연결을 나열합니다.

"활성 인터넷"열은 다음과 같습니다.

  • Proto : 이 소켓에서 사용하는 프로토콜 (예 : TCP 또는 UDP).
  • Recv-Q : 수신 큐. 수신 및 버퍼링 된 수신 바이트는이 연결을 사용하는 로컬 프로세스에서 읽고 사용하기를 기다립니다.
  • Send-Q :  전송 대기열입니다. 이것은 송신 큐에서 보낼 준비가 된 바이트를 보여줍니다.
  • 로컬 주소 : 연결의 로컬 끝 주소 세부 정보입니다. 기본값은 netstat 주소의 로컬 호스트 이름과 포트의 서비스 이름을 표시하는 것입니다.
  • 외부 주소 :  연결 원격 끝의 주소 및 포트 번호입니다.
  • 상태 : 로컬 소켓의 상태입니다. UDP 소켓의 경우 일반적으로 비어 있습니다. 아래의 상태 표를 참조하십시오 .

TCP 연결의 경우 상태 값은 다음 중 하나 일 수 있습니다.

  • 듣기 : 서버 측만. 소켓이 연결 요청을 기다리고 있습니다.
  • SYN-SENT : 클라이언트 측 전용입니다. 이 소켓은 연결 요청을했으며 수락 여부를 기다리고 있습니다.
  • SYN-RECEIVED : 서버 측 전용. 이 소켓은 연결 요청을 수락 한 후 연결 승인을 기다리고 있습니다.
  • ESTABLISHED : 서버 및 클라이언트. 서버와 클라이언트간에 작업 연결이 설정되어 둘간에 데이터를 전송할 수 있습니다.
  • FIN-WAIT-1 : 서버 및 클라이언트. 이 소켓은 원격 소켓의 연결 종료 요청 또는 이전에이 소켓에서 전송 된 연결 종료 요청의 승인을 기다리고 있습니다.
  • FIN-WAIT-2 : 서버 및 클라이언트. 이 소켓은 원격 소켓에서 연결 종료 요청을 기다리고 있습니다.
  • CLOSE-WAIT: Server and client. This socket is waiting for a connection termination request from the local user.
  • CLOSING: Server and clients. This socket is waiting for a connection termination request acknowledgment from the remote socket.
  • LAST-ACK: Server and client. This socket is waiting for an acknowledgment of the connection termination request it sent to the remote socket.
  • TIME-WAIT: Server and clients. This socket sent an acknowledgment to the remote socket to let it know that it received the remote socket’s termination request. It is now waiting to make sure that acknowledgment was received.
  • CLOSED: There is no connection, so the socket has been terminated.

The “Unix domain” columns are:

  • Proto: The protocol used by this socket. It will be “unix.”
  • RefCnt: Reference count. The number of attached processes connected to this socket.
  • Flags: This is usually set to ACC , which represents SO_ACCEPTON, meaning the socket is waiting for a connection request. SO_WAITDATA, shown as W, means there is data waiting to be read. SO_NOSPACE, shown as N, means there is no space to write data to the socket (i.e., the send buffer is full).
  • Type: The socket type. See the type table below.
  • State: The state of the socket. See the state table below.
  • I-Node: The file system inode associated with this socket.
  • Path: The file system path to the socket.

The Unix domain socket type can be one of the following:

  • DGRAM: The socket is being used in datagram mode, using messages of fixed length. Datagrams are neither guaranteed to be reliable, sequenced, nor unduplicated.
  • STREAM: This socket is a stream socket. This is the commonplace “normal” type of socket connection. These sockets are designed to provide reliable sequenced (in-order) delivery of packets.
  • RAW: This socket is being used as a raw socket. Raw sockets operate at the network level of the OSI Model and don’t reference TCP and UDP headers from the transport level.
  • RDM: This socket is located on one end of a reliably delivered messages connection.
  • SEQPACKET: This socket is operating as a sequential packet socket, which is another means of providing reliable, sequenced, and unduplicated packet delivery.
  • PACKET: Raw interface access socket. Packet sockets are used to receive or send raw packets at the device driver (i.e., data link layer) level of the OSI model.

The Unix domain socket state can be one of the following:

  • FREE: This socket is unallocated.
  • LISTENING: This socket is listening for incoming connection requests.
  • CONNECTING: This socket is in the process of connecting.
  • CONNECTED: A connection has been established, and the socket is able to receive and transmit data.
  • DISCONNECTING: The connection is in the process of being terminated.

Wow, that’s a lot of information! Many of the netstat options refine the results in one way or another, but they don’t change the content too much. Let’s take a look.

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 | less

The display out is greatly reduced. The few sockets that are listed are all TCP sockets.

The -u (UDP) and -x (UNIX) options behave in a similar way, restricting the results to the type of socket specified on the command line. Here’s the -u (UDP) option in use:

netstat -au | less

Only UDP sockets are listed.

Listing Sockets by State

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

netstat -l | less

The sockets that are listed are those that are in the listening state.

This can be combined with the -t (TCP, -u (UDP) and -x (UNIX) options to further home in on the sockets of interest. Let’s look for listening TCP sockets:

netstat -lt | less

Now, we see only TCP listening sockets.

Network Statistics by Protocol

To see statistics for a protocol, use the -s (statistics) option and pass in the -t (TCP), -u (UDP), or -x (UNIX) options. If you just use the -s (statistics) option on its own, you’ll see statistics for all protocols. Let’s check the statistics for the TCP protocol.

netstat -st | less

A collection of statistics for the TCP connections is displayed in less.

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.

sudo netstat -p -at

Here’s that output in a formatted table:

Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name  tcp 0 0 localhost:domain 0.0.0.0:* LISTEN 6927/systemd-resolv  tcp 0 0 0.0.0.0:ssh 0.0.0.0:* LISTEN 751/sshd  tcp 0 0 localhost:ipp 0.0.0.0:* LISTEN 7687/cupsd  tcp 0 0 localhost:smtp 0.0.0.0:* LISTEN 1176/master  tcp6 0 0 [::]:ssh [::]:* LISTEN 751/sshd  tcp6 0 0 ip6-localhost:ipp [::]:* LISTEN 7687/cupsd  tcp6 0 0 ip6-localhost:smtp [::]:* LISTEN 1176/master

We’ve got an extra column called “PID/program name.” This column lists the PID and name of the process using each of the sockets.

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:

sudo netstat -an | less

The IP addresses are shown as numeric values. The port numbers are also shown, separated by a colon ” : ” from the IP Address.

An IP address of 127.0.0.1 shows that the socket is bound to the loopback address of the local computer. You can think of an IP address of 0.0.0.0 as meaning the “default route” for local addresses, and “any IP address” for foreign addresses. IPv6 addresses shown as “::” are also all zero addresses.

The ports that are listed can be easily checked to see what their usual purpose is:

  • 22: This is the Secure Shell (SSH) listening port.
  • 25: This the Simple Mail Transfer Protocol (SMTP) listening port.
  • 53: This is the Domain Name System (DNS) listening port.
  • 68: This is the Dynamic Host Configuration Protocol (DHCP) listening port.
  • 631: This is the Common UNIX Printing System (CUPS) listening port.

RELATED:What is the Difference Between 127.0.0.1 and 0.0.0.0?

Displaying the Routing Table

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

sudo netstat -r

Here’s that output in a neat table:

Kernel IP routing table Destination   Gateway       Genmask        Flags  MSS Window  irtt  Iface default       Vigor.router  0.0.0.0        UG       0  0          0 enp0s3 link-local    0.0.0.0       255.255.0.0    U       0  0          0 enp0s3 192.168.4.0   0.0.0.0       255.255.255.0 U       0  0          0 enp0s3

And, here’s what the columns mean:

  • Destination: The destination network or destination host device (if the destination is not a network).
  • Gateway: The gateway address. An asterisk “*” appears here if a gateway address is not set.
  • Genmask: The subnet mask for the route.
  • Flags: See the flags table, below.
  • MSS: Default Maximum Segment Size for TCP connections over this route—this is the largest amount of data that can be received in one TCP segment.
  • Window: The default window size for TCP connections over this route, indicating the number of packets that can be transferred and received before the receiving buffer is full. In practice, the packets are consumed by the receiving application.
  • irtt: The Initial Round Trip Time. This value is referenced by the kernel to make dynamic adjustments to TCP parameters for remote connections that are slow to respond.
  • Iface: The network interface from which the packets sent over this route are transmitted.

The flags value can be one of:

  • U: The route is up.
  • H: Target is a host and the only destination possible on this route.
  • G: Use the gateway.
  • R: Reinstate the route for dynamic routing.
  • D: Dynamically installed by the routing daemon.
  • M: Modified by the routing daemon when it received an Internet Control Message Protocol (ICMP) packet.
  • A: Installed by addrconf, the automated DNS and DHCP config file generator.
  • C: Cache entry.
  • !: Reject route.

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.”

sudo netstat -anp | grep "sshd"

grep finds the target string, and we see that the sshd daemon is using port 22.

Of course, we can also do this in reverse. If we search for “:22”, we can find out which process is using that port, if any.

sudo netstat -anp | grep ":22"

This time grep finds the “:22” target string, and we see that the process using this port is the sshd daemon, process ID 751.

List the Network Interfaces

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

sudo netstat -i

Here’s the output in a more legible fashion:

Kernel Interface table Iface    MTU   RX-OK  RX-ERR RX-DRP  RX-OVR   TX-OK   TX-ERR   TX-DRP   TX-OVR Flg enp0s3   1500 4520671 0 0 0 4779773 0 0 0 BMRU lo 65536 30175 0 0 0 30175 0 0 0 LRU

This is what the columns mean:

  • Iface: The name of the interface. The enp0s3 interface is the network interface to the outside world, and the lo interface is the loopback interface. The loopback interface enables processes to intercommunicate within the computer using networking protocols, even if the computer is not connected to a network.
  • MTU: The Maximum Transmission Unit (MTU). This is the largest “packet” that can be sent. It consists of a header containing routing and protocol flags, and other metadata, plus the data that is actually being transported.
  • RX-OK: The number of packets received, with no errors.
  • RX-ERR: The number of packets received, with errors. We want this to be as low as possible.
  • RX-DRP: The number of packets dropped (i.e., lost). We also want this to be as low as possible.
  • RX-OVR: Number of packets lost due to overflows when receiving. This usually means that the receiving buffer was full and could not accept any more data, but more data was received and had to be discarded. The lower this figure, the better, and zero is perfect.
  • TX-OK: The number of packets transmitted, with no errors.
  • RX-ERR: The number of packets transmitted, with errors. We want this to be zero.
  • RX-DRP: The number of packets dropped when transmitting. Ideally, this should be zero.
  • RX-OVR: The number of packets lost due to overflows when transmitting. This usually means the send buffer was full and could not accept any more data, but more data was was ready to be transmitted and had to be discarded.
  • Flg: Flags. See the flags table below.

The flags represent the following:

  • B: A broadcast address is in use.
  • L: This interface is a loopback device.
  • M: All packets are being received (i.e., in promiscuous mode). Nothing is filtered or discarded.
  • O: Address Resolution Protocol (ARP) is turned off for this interface.
  • P: This is a Point-to-Point (PPP) connection.
  • R: The interface is running.
  • U: The interface is up.

List Multicast Group Memberships

Simply put, a multicast transmission enables a packet to be sent only once, regardless of the number of recipients. For services such as video streaming, for example, this increases the efficiency from the sender’s point of view by a tremendous amount.

The -g (groups) option makes netstat list the multicast group membership of sockets on each interface.

sudo netstat -g

The columns are quite simple:

  • Interface: The name of the interface over which the socket is transmitting.
  • RefCnt: The reference count, which is the number of processes attached to the socket.
  • Group: The name or identifier of the multicast group.

The New Kids on the Block

The route, ip, ifconfig, and ss commands can provide a lot of what netstat is capable of showing you. They’re all great commands and worth checking out.

We’ve focused on netstat because it is universally available, regardless of which Unix-like operating system you’re working on, even the obscure ones.