Linux'ta netstat nasıl kullanılır

Linux netstatkomutu size ağ bağlantılarınız, kullanımda olan bağlantı noktaları ve bunları kullanan işlemler hakkında bir bilgi hazinesini verir. Nasıl kullanılacağını öğrenin.

Bağlantı Noktaları, İşlemler ve Protokoller

Ağ soketleri bağlanabilir veya bir bağlantı beklenebilir. Bağlantılar, Taşıma Kontrol Protokolü (TCP) veya Kullanıcı Datagram Protokolü UDP gibi ağ protokollerini kullanır. Bağlantı kurmak için İnternet Protokolü adreslerini ve ağ bağlantı noktalarını kullanırlar.

Sözcük soketleri   , bir uç veya kablo için fiziksel bir bağlantı noktasının görüntülerini çağrıştırabilir, ancak bu bağlamda, bir soket, bir ağ veri bağlantısının bir ucunu işlemek için kullanılan bir yazılım yapısıdır.

Soketlerin iki ana durumu vardır: Ya bağlanırlar ve devam eden bir ağ iletişimini kolaylaştırırlar ya da gelen bir bağlantının kendilerine bağlanmasını beklerler . Bir soketin uzak bir cihazda bağlantı kurmanın ortasında olması gibi başka durumlar da vardır, ancak geçici durumları bir kenara bırakarak, bir soketi bağlı veya bekleme olarak düşünebilirsiniz (buna genellikle dinleme denir ).

Dinleme soketine sunucu adı verilir ve dinleme soketiyle bağlantı isteyen sokete istemci adı verilir . Bu isimlerin donanım veya bilgisayar rolleriyle ilgisi yoktur. Bağlantının her iki ucundaki her soketin rolünü basitçe tanımlarlar.

netstatKomut Eğer prizler bağlanır ve prizler dinlerken hangi keşfetmesine olanak sağlar. Anlamı, hangi bağlantı noktalarının kullanımda olduğunu ve hangi işlemlerin bunları kullandığını size söyler. Ağ arayüzleriniz ve çok noktaya yayın bağlantılarınız hakkında size yönlendirme tabloları ve istatistikleri gösterebilir.

İşlevselliği, netstatip ve ss gibi farklı Linux araçlarında zamanla çoğaltılmıştır. Hala tüm ağ analizi komutlarının bu atasını bilmeye değer, çünkü tüm Linux ve Unix benzeri işletim sistemlerinde ve hatta Windows ve Mac'te mevcut.

İşte nasıl kullanılacağı, örnek komutlarla tamamlandı.

Tüm Soketleri Listeleme

-a(Tümü) seçeneği markaları netstatbağlı tüm ve bekleyen yuvalarını gösterir. Bu komut uzun bir liste oluşturmakla yükümlüdür, bu yüzden onu içine aktarıyoruz less.

netstat -a | az

Liste, TCP (IP), TCP6 (IPv6) ve UDP soketlerini içerir.

Terminal penceresindeki sarmalama, neler olup bittiğini görmeyi biraz zorlaştırır. İşte bu listeden birkaç bölüm:

Aktif İnternet bağlantıları (sunucular ve kurulmuş) Proto Recv-Q Send-Q Yerel Adres Yabancı Adres Durumu tcp 0 0 localhost: etki alanı 0.0.0.0:* DİNLE tcp 0 0 0.0.0.0:ssh 0.0.0.0:* DİNLE tcp 0 0 localhost : ipp 0.0.0.0:* DİNLE tcp 0 0 localhost: smtp 0.0.0.0:* DİNLE tcp6 0 0 [::]: ssh [::]: * DİNLE tcp6 0 0 ip6-localhost: ipp [::]: * DİNLE. . . Aktif UNIX alan soketleri (sunucular ve kurulmuş) Proto RefCnt Bayrakları Tip Durum I-Düğüm Yolu 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

"Aktif İnternet" bölümü, bağlı harici bağlantıları ve uzak bağlantı isteklerini dinleyen yerel soketleri listeler. Yani, harici cihazlara kurulan (veya kurulacak) ağ bağlantılarını listeler.

"UNIX etki alanı" bölümü, bağlı ve dinleyen dahili bağlantıları listeler. Başka bir deyişle, bilgisayarınızda farklı uygulamalar, işlemler ve işletim sisteminin öğeleri arasında kurulan bağlantıları listeler.

"Aktif İnternet" sütunları şunlardır:

  • Proto: Bu soket tarafından kullanılan protokol (örneğin, TCP veya UDP).
  • Recv-Q: Alım kuyruğu. Bunlar, alınan ve arabelleğe alınan, bu bağlantıyı kullanan yerel işlemin okuyup tüketmesini bekleyen gelen baytlardır.
  • Send-Q:  Gönderme kuyruğu. Bu, gönderme kuyruğundan gönderilmeye hazır olan baytları gösterir.
  • Yerel adres: Bağlantının yerel ucunun adres ayrıntıları. Varsayılan, netstat adres için yerel ana bilgisayar adını ve bağlantı noktası için hizmet adını göstermektir.
  • Yabancı adres:  Bağlantının uzak ucunun adresi ve bağlantı noktası numarası.
  • Durum: Yerel soketin durumu. UDP soketleri için bu genellikle boştur. Bkz devlet Aşağıdaki tabloya.

TCP bağlantıları için durum değeri aşağıdakilerden biri olabilir:

  • DİNLE: Yalnızca sunucu tarafı. Soket bir bağlantı talebini bekliyor.
  • SYN-SENT: Yalnızca istemci tarafı. Bu soket bir bağlantı isteğinde bulundu ve kabul edilip edilmeyeceğini görmek için bekliyor.
  • SYN-RECEIVED: Yalnızca sunucu tarafı. Bu soket, bir bağlantı talebini kabul ettikten sonra bağlantı onayını bekliyor.
  • KURULUŞ: Sunucu ve istemciler. Sunucu ve istemci arasında, verilerin ikisi arasında aktarılmasına izin veren çalışan bir bağlantı kuruldu.
  • FIN-WAIT-1: Sunucu ve istemciler. Bu yuva, uzaktaki soketten bir bağlantı sonlandırma isteği veya daha önce bu soketten gönderilmiş bir bağlantı sonlandırma talebinin onayını bekliyor.
  • FIN-WAIT-2: Sunucu ve istemciler. Bu soket, uzak soketten bir bağlantı sonlandırma isteği bekliyor.
  • CLOSE-WAIT: Sunucu ve istemci. Bu soket, yerel kullanıcıdan bir bağlantı sonlandırma talebi bekliyor.
  • KAPANIŞ: Sunucu ve istemciler. Bu soket, uzak soketten bağlantı sonlandırma talebi onayını bekliyor.
  • LAST-ACK: Sunucu ve istemci. Bu soket, uzak sokete gönderdiği bağlantı sonlandırma talebinin onaylanmasını bekliyor.
  • TIME-WAIT: Sunucu ve istemciler. Bu soket, uzak soketin sonlandırma talebini aldığını bildirmek için uzak sokete bir alındı ​​bildirimi gönderdi. Şimdi, onayın alındığından emin olmak için bekliyor.
  • KAPALI: Bağlantı yok, bu nedenle soket sonlandırıldı.

"Unix alanı" sütunları şunlardır:

  • Proto: Bu soket tarafından kullanılan protokoldür. "Unix" olacaktır.
  • RefCnt: Referans sayısı. Bu sokete bağlı ekli işlemlerin sayısı.
  • Bayraklar: Bu genellikle olarak ayarlanır ACC , bu SO_ACCEPTONda soketin bir bağlantı talebini beklediği anlamına gelir. SO_WAITDATAOlarak gösterilen Waracı, veri okuma için bekleyen vardır. SO_NOSPACE, olarak gösterilen N, sokete veri yazmak için yer olmadığı anlamına gelir (yani, gönderme arabelleği dolu).
  • Tür: Soket türü. Bkz tipi aşağıdaki tabloya.
  • Durum: Soketin durumu. Bkz devlet aşağıdaki tabloya.
  • I-Node: Bu soket ile ilişkili dosya sistemi inode.
  • Yol : Sokete giden dosya sistemi yolu.

Unix etki alanı soket türü aşağıdakilerden biri olabilir:

  • DGRAM: Soket, sabit uzunluktaki mesajlar kullanılarak datagram modunda kullanılıyor. Datagramların güvenilir, sıralı veya kopyalanmamış olduğu garanti edilmez.
  • STREAM: Bu soket bir akış soketidir. Bu, sıradan "normal" tip soket bağlantısıdır. Bu soketler, paketlerin güvenilir sıralı (sırayla) teslimini sağlamak için tasarlanmıştır.
  • RAW: Bu soket ham soket olarak kullanılıyor. Ham soketler, OSI Modelinin ağ seviyesinde çalışır ve taşıma seviyesinden TCP ve UDP başlıklarına başvurmaz.
  • RDM: Bu soket, güvenilir bir şekilde iletilen mesaj bağlantısının bir ucunda bulunur.
  • SEQPACKET: Bu soket, güvenilir, sıralı ve tekilleştirilmemiş paket teslimatı sağlamanın başka bir yolu olan sıralı bir paket soketi olarak çalışır.
  • PAKET: Ham arayüz erişim soketi. Paket soketleri, OSI modelinin aygıt sürücüsü (yani veri bağlantı katmanı) seviyesinde ham paketleri almak veya göndermek için kullanılır.

Unix etki alanı soket durumu aşağıdakilerden biri olabilir:

  • ÜCRETSİZ: Bu soket ayrılmamış.
  • DİNLEME: Bu soket gelen bağlantı isteklerini dinliyor.
  • BAĞLANIYOR: Bu soket bağlanma sürecindedir.
  • BAĞLANDI: Bir bağlantı kuruldu ve soket veri alıp iletebiliyor.
  • 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.