Linuxでnetstatを使用する方法

Linuxnetstatコマンドは、ネットワーク接続、使用中のポート、およびそれらを使用するプロセスに関する情報の宝庫を提供します。それを使用する方法を学びます。

ポート、プロセス、およびプロトコル

ネットワークソケットは、接続することも、接続を待機することもできます。接続は、トランスポート制御プロトコル(TCP)やユーザーデータグラムプロトコルUDPなどのネットワークプロトコルを使用します。インターネットプロトコルアドレスとネットワークポートを使用して接続を確立します。

ソケットという言葉  は、リード線またはケーブルの物理的な接続ポイントのイメージを想起させる場合がありますが、このコンテキストでは、ソケットはネットワークデータ接続の一端を処理するために使用されるソフトウェア構造です。

ソケットには2つの主要な状態があります。ソケットは接続されて進行中のネットワーク通信を促進するか、着信接続がソケットに接続するのを待っています。ソケットがリモートデバイスで接続を確立している途中の状態など、他の状態もありますが、一時的な状態は別として、ソケットは接続中または待機中(リスニングと呼ばれることが多い)と考えることができます。

リスニングソケットはサーバーと呼ばれ、リスニングソケットとの接続を要求するソケットはクライアントと呼ばれます。これらの名前は、ハードウェアやコンピューターの役割とは何の関係もありません。これらは、接続の両端で各ソケットの役割を定義するだけです。

このnetstatコマンドを使用すると、接続されているソケットとリッスンしているソケットを検出できます。つまり、どのポートが使用されており、どのプロセスがそれらを使用しているかがわかります。ネットワークインターフェイスとマルチキャスト接続に関するルーティングテーブルと統計を表示できます。

の機能はnetstat、ipやssなどのさまざまなLinuxユーティリティで時間の経過とともに複製されてきました。すべてのLinuxおよびUnixライクなオペレーティングシステム、さらにはWindowsおよびMacでも使用できるため、すべてのネットワーク分析コマンドのこのおじいちゃんを知ることは依然として価値があります。

使用方法は次のとおりで、コマンドの例が含まれています。

すべてのソケットの一覧表示

-a(すべての)オプションますがnetstat、すべての接続待機中のソケットを示しています。このコマンドは長いリストを生成する傾向があるため、にパイプしlessます。

netstat -a | もっと少なく

リストには、TCP(IP)、TCP6(IPv6)、およびUDPソケットが含まれます。

ターミナルウィンドウのラップアラウンドにより、何が起こっているのかを確認するのが少し難しくなります。そのリストからいくつかのセクションがあります:

アクティブなインターネット接続(サーバーおよび確立済み)Proto Recv-QSend-Qローカルアドレス外部アドレス状態tcp0 0 localhost:domain 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:ssh 0.0.0.0:* LISTEN tcp 0 0 localhost :ipp 0.0.0.0:* LISTEN tcp 0 0 localhost:smtp 0.0.0.0:* LISTEN tcp6 0 0 [::]:ssh [::]:* LISTEN tcp6 0 0 ip6-localhost:ipp [::]:*聞く。 。 。アクティブなUNIXドメインソケット(サーバーおよび確立済み)ProtoRefCntフラグタイプ状態I-ノードパスunix24 [] 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:サーバー側のみ。このソケットは、接続要求を受け入れた後、接続確認応答を待機しています。
  • 確立済み:サーバーとクライアント。サーバーとクライアントの間に正常な接続が確立され、2つの間でデータを転送できるようになりました。
  • FIN-WAIT-1:サーバーとクライアント。このソケットは、リモートソケットからの接続終了要求、またはこのソケットから以前に送信された接続終了要求の確認応答を待機しています。
  • FIN-WAIT-2:サーバーとクライアント。このソケットは、リモートソケットからの接続終了要求を待機しています。
  • CLOSE-WAIT:サーバーとクライアント。このソケットは、ローカルユーザーからの接続終了要求を待機しています。
  • クロージング:サーバーとクライアント。このソケットは、リモートソケットからの接続終了要求の確認応答を待機しています。
  • LAST-ACK:サーバーとクライアント。このソケットは、リモートソケットに送信した接続終了要求の確認応答を待機しています。
  • TIME-WAIT:サーバーとクライアント。このソケットは、リモートソケットに確認応答を送信して、リモートソケットの終了要求を受信したことを通知します。現在、確認応答が受信されたことを確認するのを待っています。
  • CLOSED:接続がないため、ソケットは終了しました。

「Unixドメイン」列は次のとおりです。

  • Proto:このソケットで使用されるプロトコル。「unix」になります。
  • RefCnt:参照カウント。このソケットに接続されている接続済みプロセスの数。
  • フラグ:これは通常に設定されているACC 表し、SO_ACCEPTONソケットが接続要求を待っている意味します、。 SO_WAITDATAとして示されているはW、読み取りを待機しているデータがあることを意味します。SO_NOSPACEとして示されNているは、ソケットにデータを書き込むスペースがないことを意味します(つまり、送信バッファーがいっぱいです)。
  • タイプ:ソケットタイプ。以下のタイプ表を参照してください。
  • 状態:ソケットの状態。以下の状態表を参照してください。
  • Iノード:このソケットに関連付けられているファイルシステムのiノード。
  • パス:ソケットへのファイルシステムパス。

Unixドメインソケットタイプは、次のいずれかになります。

  • DGRAM:ソケットは、固定長のメッセージを使用して、データグラムモードで使用されています。データグラムは、信頼性、順序付け、または複製解除が保証されていません。
  • STREAM:このソケットはストリームソケットです。これは、ありふれた「通常の」タイプのソケット接続です。これらのソケットは、パケットの信頼性の高いシーケンス(順序)配信を提供するように設計されています。
  • RAW:このソケットはrawソケットとして使用されています。rawソケットは、OSIモデルのネットワークレベルで動作し、トランスポートレベルからTCPおよびUDPヘッダーを参照しません。
  • RDM:このソケットは、確実に配信されるメッセージ接続の一方の端にあります。
  • SEQPACKET:このソケットは、シーケンシャルパケットソケットとして動作します。これは、信頼性が高く、シーケンスされた、重複のないパケット配信を提供するもう1つの手段です。
  • PACKET:生のインターフェースアクセスソケット。パケットソケットは、OSIモデルのデバイスドライバー(つまり、データリンク層)レベルで生のパケットを送受信するために使用されます。

Unixドメインソケットの状態は、次のいずれかになります。

  • 無料:このソケットは割り当てられていません。
  • リスニングこのソケットは、着信接続要求をリッスンしています。
  • 接続中:このソケットは接続中です。
  • CONNECTED:接続が確立され、ソケットはデータを送受信できます。
  • 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.