Софт-Архив

Netstat img-1

Netstat

Рейтинг: 4.1/5.0 (1901 проголосовавших)

Категория: Windows: Мониторинг

Описание

Команда Netstat

Параметры команды Netstat

Вывод всех активных подключений TCP и прослушиваемых компьютером портов TCP и UDP.

Вывод статистики Ethernet, например количества отправленных и принятых байтов и пакетов. Этот параметр может комбинироваться с ключом -s .

Вывод активных подключений TCP с отображением адресов и номеров портов в числовом формате без попыток определения имен.

вывод активных подключений TCP и включение кода процесса (PID) для каждого подключения. Код процесса позволяет найти приложение на вкладке Процессы диспетчера задач Windows. Этот параметр может комбинироваться с ключами -a. -n и -p .

Вывод подключений для протокола, указанного параметром протокол. В этом случае параметр протокол может принимать значения tcp. udp. tcpv6 или udpv6. Если данный параметр используется с ключом -s для вывода статистики по протоколу, параметр протокол может иметь значение tcp. udp. icmp. ip. tcpv6. udpv6. icmpv6 или ipv6 .

Вывод статистики по протоколу. По умолчанию выводится статистика для протоколов TCP, UDP, ICMP и IP. Если установлен протокол IPv6 для Windows XP, отображается статистика для протоколов TCP через IPv6, UDP через IPv6, ICMPv6 и IPv6. Параметр -p может использоваться для указания набора протоколов.

Вывод содержимого таблицы маршрутизации IP. Эта команда эквивалентна команде route print .

Обновление выбранных данных с интервалом, определенным параметром интервал (в секундах). Нажатие клавиш CTRL+C останавливает обновление. Если этот параметр пропущен, netstat выводит выбранные данные только один раз.

Отображение справки в командной строке.

Примечания
  • Параметрам, используемым с данной командой, должен предшествовать дефис (- ), а не косая черта (/ ).
  • Команда Netstat выводит статистику для следующих объектов.
    • Протокол

Имя протокола (TCP или UDP).

IP-адрес локального компьютера и номер используемого порта. Имя локального компьютера, соответствующее IP-адресу и имени порта, выводится только в том случае, если не указан параметр -n. Если порт не назначен, вместо номера порта будет выведена звездочка (*).

Другие статьи, обзоры программ, новости

Microsoft Windows XP

Displays active TCP connections, ports on which the computer is listening, Ethernet statistics, the IP routing table, IPv4 statistics (for the IP, ICMP, TCP, and UDP protocols), and IPv6 statistics (for the IPv6, ICMPv6, TCP over IPv6, and UDP over IPv6 protocols). Used without parameters, netstat displays active TCP connections.

netstat  [-a ] [-e ] [-n ] [-o ] [-p  Protocol ] [-r ] [-s ] [Interval ]

Parameters

-a   : Displays all active TCP connections and the TCP and UDP ports on which the computer is listening.

-e   : Displays Ethernet statistics, such as the number of bytes and packets sent and received. This parameter can be combined with -s.

-n   : Displays active TCP connections, however, addresses and port numbers are expressed numerically and no attempt is made to determine names.

-o   : Displays active TCP connections and includes the process ID (PID) for each connection. You can find the application based on the PID on the Processes tab in Windows Task Manager. This parameter can be combined with -a. -n. and -p.

-p   Protocol   : Shows connections for the protocol specified by Protocol. In this case, the Protocol can be tcp. udp. tcpv6. or udpv6. If this parameter is used with -s to display statistics by protocol, Protocol can be tcp. udp. icmp. ip. tcpv6. udpv6. icmpv6. or ipv6.

-s   : Displays statistics by protocol. By default, statistics are shown for the TCP, UDP, ICMP, and IP protocols. If the IPv6 protocol for Windows XP is installed, statistics are shown for the TCP over IPv6, UDP over IPv6, ICMPv6, and IPv6 protocols. The -p parameter can be used to specify a set of protocols.

-r   : Displays the contents of the IP routing table. This is equivalent to the route print command.

Interval   : Redisplays the selected information every Interval seconds. Press CTRL+C to stop the redisplay. If this parameter is omitted, netstat prints the selected information only once.

/?   : Displays help at the command prompt.

Linux and Unix netstat command help

About netstat

In the syntax above, address_family_options may be any combination of the following options:

Description

netstat ("network statistics") is a command-line tool that displays network connections (both incoming and outgoing), routing tables, and a number of network interface (network interface controller or software-defined network interface) and network protocol statistics. It is available on Unix -like operating systems including OS X. Linux. Solaris. and BSD. and on Windows NT -based operating systems including Windows XP. Windows Vista. Windows 7 and Windows 8 .

Output: Internet Connections

statistics.

Displays generic statistics about the network activity of the local system.

Shows information about all active connections to the server, including the source and destination IP addresses and ports, if you have proper permissions.

Displays the routing table for all IP addresses bound to the server.

Collects statistics about the amount of active connections on port 80, and pipes this data to the wc command, which displays the number of connections by counting the lines of the original netstat output.

Related commands

ac — Print statistics about the amount of time users have been connected.

arp — Manipulate the system ARP cache.

ifconfig — View or modify the configuration of network interfaces.

10 basic examples of linux netstat command

10 basic examples of linux netstat command

Netstat is a command line utility that can be used to list out all the network (socket) connections on a system. It lists out all the tcp, udp socket connections and the unix socket connections.

Apart from connected sockets it can also list listening sockets that are waiting for incoming connections. So by verifying an open port 80 you can confirm if a web server is running on the system or not. This makes it a very useful tool for network and system administrators.

In this tutorial we shall be checking out few examples of how to use netstat to find information about network connections and open ports on a system.

Here is a quick intro to netstat from the man pages

1. List out all connections

The first and most simple command is to list out all the current connections. Simply run the netstat command with the a option.

The above command shows all connections from different protocols like tcp, udp and unix sockets. However this is not quite useful. Administrators often want to pick out specific connections based on protocols or port numbers for example.

2. List only TCP or UDP connections

To list out only tcp connections use the t options.

Similarly to list out only udp connections use the u option.

The above output shows both ipv4 and ipv6 connections.

3. Disable reverse dns lookup for faster output

By default, the netstat command tries to find out the hostname of each ip address in the connection by doing a reverse dns lookup. This slows down the output. If you do not need to know the host name and just the ip address is sufficient then suppress the hostname lookup with the n option.

The above command shows ALL TCP connections with NO dns resolution. Got it. Good.

4. List out only listening connections

Any network daemon/service keeps an open port to listen for incoming connections. These too are like socket connections and are listed out by netstat. To view only listening ports use the l options.

Now we can see only listening tcp ports/connections. If you want to see all listening ports, remove the t option. If you want to see only listening udp ports use the u option instead of t.

Make sure to remove the 'a' option, otherwise all connections would get listed and not just the listening connections.

5. Get process name/pid and user id

When viewing the open/listening ports and connections, its often useful to know the process name/pid which has opened that port or connection. For example the Apache httpd server opens port 80. So if you want to check whether any http server is running or not, or which http server is running, apache or nginx, then track down the process name.

The process details are made available by the 'p' option.

When using the p option, netstat must be run with root privileges, otherwise it cannot detect the pids of processes running with root privileges and most services like http and ftp often run with root privileges.

Along with process name/pid its even more useful to get the username/uid owning that particular process. Use the e option along with the p option to get the username too.

The above example lists out Listening connections of Tcp type with Process information and Extended information.

The extended information contains the username and inode of the process. This is a useful command for network administrators.

Note - If you use the n option with the e option, the uid would be listed and not the username.

6. Print statistics

The netstat command can also print out network statistics like total number of packets received and transmitted by protocol type and so on.

To list out statistics of all packet types

To print out statistics of only select protocols like TCP or UDP use the corresponding options like t and u along with the s option. Simple!

7. Display kernel routing information

The kernel routing information can be printed with the r option. It is the same output as given by the route command. We also use the n option to disable the hostname lookup.

8. Print network interfaces

The netstat command can also print out the information about the network interfaces. The i option does the task.

The above output contains information in a very raw format. To get a more human friendly version of the output use the e option along with i.

The above output is similar to the output shown by the ifconfig command.

9. Get netstat output continuously

Netstat can output connection information continuously with the c option.

The above command will output tcp connections continuously.

10. Display multicast group information

The g option will display the multicast group information for IPv4 and IPv6 protocols.

More examples of netstat command

Okay, we covered the basic examples of netstat command above. Now its time to do some geek stuff with style.

Print active connections

Active socket connections are in "ESTABLISHED" state. So to get all current active connections use netstat with grep as follows

And do leave your feedback and suggestions in the comments box below.

Netstat(8) - Linux man page

netstat(8) - Linux man page

netstat - Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships

netstat [address_family_options ] [--tcp |-t ] [--udp |-u ] [--raw |-w ] [--listening |-l ] [--all |-a ] [--numeric |-n ] [--numeric-hosts ][ --numeric-ports] [--numeric-ports ] [--symbolic |-N ] [--extend |-e [--extend |-e] ] [--timers |-o ] [--program |-p ] [--verbose |-v ] [--continuous |-c] [delay]

netstat <--route |-r > [address_family_options ] [--extend |-e [--extend |-e] ] [--verbose |-v ] [--numeric |-n ] [--numeric-hosts ][ --numeric-ports] [--numeric-ports ] [--continuous |-c] [delay]

netstat <--interfaces |-I |-i > [iface ] [--all |-a ] [--extend |-e ] [--verbose |-v ] [--program |-p ] [--numeric |-n ] [--numeric-hosts ][ --numeric-ports] [--numeric-ports ] [--continuous |-c] [delay]

netstat <--groups |-g > [--numeric |-n ] [--numeric-hosts ][ --numeric-ports] [--numeric-ports ] [--continuous |-c] [delay]

netstat <--masquerade |-M > [--extend |-e ] [--numeric |-n ] [--numeric-hosts ][ --numeric-ports] [--numeric-ports ] [--continuous |-c] [delay]

netstat <--statistics |-s > [--tcp |-t ] [--udp |-u ] [--raw |-w ] [delay]

netstat <--version |-V >

netstat <--help |-h >

address_family_options.

This program is obsolete. Replacement for netstat is ss. Replacement for netstat -r is ip route. Replacement for netstat -i is ip -s link. Replacement for netstat -g is ip maddr.

Netstat

UNIX / Linux: 10 Netstat Command Examples

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

2. List Sockets which are in Listening State 3. Show the statistics for each protocol Show statistics for TCP (or) UDP ports using netstat -st (or) -su 4. Display PID and program names in netstat output using netstat -p

netstat -p option can be combined with any other netstat option. This will add the “PID/Program Name” to the netstat output. This is very useful while debugging to identify which program is running on a particular port.

5. Don’t resolve host, port and user name in netstat output

When you don’t want the name of the host, port or user to be displayed, use netstat -n option. This will display in numbers, instead of resolving the host name, port name, user name.

If you don’t want only any one of those three items ( ports, or hosts, or users ) to be resolved, use following commands.

6. Print netstat information continuously

netstat will print information continuously every few seconds.

7. Find the non supportive Address families in your system 8. Display the kernel routing information using netstat -r

Netstat

The netstat command is used to query the routing table of the local host and that status of TCP/IP networking. In Solaris the command is located in the /usr/bin directory. In Linux /bin/netstat. Options are pretty much common (which is a rare thing :-)

When used with the -i option, netstat displays the state of the Ethernet interfaces, with r option it displayed routing information and with -s option statistical information:

  • netstat -i # the state of the Ethernet interfaces
  • netstat -r # displays routing info
  • netstat -s # statistical information

One of the more useful options is:

The `-p` options tells it to try to determine what program has the socket open, which is often very useful info. For example, someone nmap's their system and wants to know what is using port 666 for example. Running netstat -pa will show you its satand running on that tcp port.

One of the most twisted, but useful invocations is:

This will show you a sorted list of how many sockets are in each connection state. For example:

The exact syntax of this command is Unix flavor dependent. In general, it can provide information on:

  • Active TCP connections at this local host.
  • State of all TCP/IP servers on this local host and the sockets used by them.
  • Devices and links used by TCP/IP.
  • The IP routing tables (gateway tables) in use at this local host.

Typical usage

netstat -r The -r switch can be used to display TCP the routing table.

netstat -rn same but without hostname lookup

  • netstat -punta List externally connected processes:
  • netstat -nap List all connected processes:
  • netstat -s Show network statistics:
  • netstat -a -i eth0 Kernel interface table info
  • # netstat -tap |grep LISTEN

    *:exec *:* LISTEN 988/inetd

    *:login *:* LISTEN 988/inetd

    *:shell *:* LISTEN 988/inetd

    *:printer *:* LISTEN 988/inetd

    *:time *:* LISTEN 988/inetd

    *:x11 *:* LISTEN 1462/X

    *:http *:* LISTEN 1078/httpd

    bigcat:domain *:* LISTEN 956/named

    bigcat:domain *:* LISTEN 956/named

    *:ssh *:* LISTEN 972/sshd

    *:auth *:* LISTEN 388/in.identd

    *:ftp *:* LISTEN 988/inetd

    *:smtp *:* LISTEN 1738/sendmail: accepting connections

    *:694 *:* LISTEN 1319/rpc.mountd

    *:netbios-ssn *:* LISTEN 422/smbd

    More extended list of typical idioms can be found at Sun Microsystems - BigAdmin Shell Commands :]

    Displaying the Routing Table

    netstat with the –r option displays the kernel routing table in the way similar to parameters supplied to the route command. For example on Red Hat linux 5.6 nestat -rn will display:

    The –n option suppresses resolution of hostnames and displays all IPs in numeric form, rather than the symbolic host and network names.

    The second column shows the gateway to which the routing entry points. If no gateway is used, an asterisk is printed with -n option and 0.0.0.0 with the -rn option.

    The third column shows the “generality” of the route, i.e. the network mask for this route. Routing table displayed by netstat is sorted in reverse length of the netmask order. Host routes have netmask 255.255.255.255 and displayed first.

    When given an IP address to find a suitable route for, the kernel iterates through each entry of the routing table taking the bitwise AND of the address and the genmask before comparing it to the target of the route.

    The fourth column displays the following flags that describe the route:

    • G -- The route uses a gateway.
    • U -- The interface to be used is up.
    • H -- Only a single host can be reached through the route. In this case Genmask column is always 255.255.255.255
    • D -- This route is dynamically created. It is set if the table entry has been generated by a routing daemon like gated or by an ICMP redirect message
    • M -- This route is set if the table entry was modified by an ICMP redirect message.
    • ! -- The route is a reject route and datagrams will be dropped.

    The next three columns show the MSS, Window and irtt that will be applied to TCP connections established via this route. The MSS is the Maximum Segment Size and is the size of the largest datagram the kernel will construct for transmission via this route. The Window is the maximum amount of data the system will accept in a single burst from a remote host. The acronym irtt stands for “initial round trip time.” The TCP protocol ensures that data is reliably delivered between hosts by retransmitting a datagram if it has been lost. The TCP protocol keeps a running count of how long it takes for a datagram to be delivered to the remote end, and an acknowledgement to be received so that it knows how long to wait before assuming a datagram needs to retransmitted; this process is called the round-trip time. The initial round-trip time is the value that the TCP protocol will use when a connection is first established. For most network types, the default value is okay, but for some slow networks, notably certain types of amateur packet radio networks, the time is too short and causes unnecessary retransmission. The irtt value can be set using the route command. Values of zero in these fields mean that the default is being used.

    Finally, the last field displays the network interface that this route will use.

    Displaying Interface Statistics

    When invoked with the -i flag, netstat displays statistics for the network interfaces currently configured.

    If the –a option is also given, it prints all interfaces present in the kernel, not only those that have been configured currently.

    The MTU and Met fields show the current MTU and metric values for that interface. The RX and TX columns show how many packets have been received or transmitted error-free (RX-OK/TX-OK) or damaged (RX-ERR/TX-ERR); how many were dropped (RX-DRP/TX-DRP); and how many were lost because of an overrun (RX-OVR/TX-OVR).

    The last column shows the flags that have been set for this interface. These characters are one-character versions of the long flag names that are printed when you display the interface configuration with ifconfig:

    • B A broadcast address has been set.
    • L This interface is a loopback device.
    • M All packets are received (promiscuous mode).
    • O ARP is turned off for this interface.
    • P This is a point-to-point connection.
    • R Interface is running.
    • U Interface is up.
    Displaying Connections

    netstat supports a set of options to display active or passive sockets. The options –t, –u, –w, and –x show active TCP, UDP, RAW, or Unix socket connections. If you provide the –a flag in addition, sockets that are waiting for a connection (i.e. listening) are displayed as well. This display will give you a list of all servers that are currently running on your system.

    Using the –a flag by itself will display all sockets from all families.

  • Terminal Mac OS X Команда терминала netstat - показать состояние сети

    Параметры команды netstat:

    По умолчанию для активных сокетов отображаются внутренние (локальные и внешние) адреса, размеры очередей на отправку и получение (в байтах), протокол и внутреннее состояние протокола. Адреса выводятся в формате "host.port" или "network.port". Если известны имя хоста и его адрес (в файлах /etc/hosts или /etc/networks ) отображается символьное имя хоста. Если неизвестно символьное имя или использован параметр -n, адрес печатается числом в соответствии с семейством адресов.

    Статусы сокетов:

    CLOSED: сокет не используется

    LISTEN: сокет ожидает входящего соединения. Не связанные ожидающие сокеты отображаются только при использовании параметра -a.

    SYN_SENT: идет попытка установки соединения с удаленным узлом в активном режиме.

    SYN_RCVD: сокет в пассивном режиме получил запрос на соединение с удаленным узлом.

    ESTABLISHED: имеется соединение между локальным приложением и удаленным узлом.

    CLOSE_WAIT: Соединение было закрыто удаленным узлом и система ожидает его закрытия локальным приложением.

    LAST_ACK:  Соединение было закрыто удаленным узлом, локальное приложение закрыло соединение и система ожидает подтверждение от удаленного узла для признания закрытым.

    FIN_WAIT_1: Локальное приложение закрыло соединение, удаленный узел не дал подтверждения о закрытии и система его ожидает.

    FIN_WAIT_2:  Локальное приложение закрыло соединение, удаленный узел дал подтверждения о закрытии и система ожидает закрытия соединения.

    CLOSING: Соединение было закрыто одновременно и локальным приложением и удаленным.

    TIME_WAIT: Соединение было закрыто локальным приложением, удаленный узел закрыл эту половину соединения и система ожидает, чтобы удаленный узел получил подтверждение о закрытии.

    Таблицы маршрутизации показывают доступные маршруты и их статус.

    Каждый маршрут состоит и адреса назначения или сети и шлюза используемого в передаче пакетов. Поле флагов отображает собранную информацию о маршруте. Индивидуальные флаги описываются в материалах route(8) и route(4). Следующая таблица описывает связь между флагами и показываемыми символами: