Monitoring Network Status With the netstat Command
The netstat command generates displays that show network status and protocol statistics. You
can display the status of TCP, SCTP, and UDP endpoints in table format.
You can also display routing table information and interface information.
This section describes the most commonly used options of the netstat command.
For a detailed description of all netstat options, refer to the netstat(1M) man page.
Текущая версия страницы пока не проверялась опытными участниками и может значительно отличаться от версии, проверенной 27 декабря 2017 года; проверки требуют 20 правок.
Эта страница — глоссарий. См. также основную статью: DOS
Список команд DOS — нижеследующий список команд для операционной системы DOS. Начиная с 5-й версии, этот список с кратким описанием каждой команды может быть получен набором команды HELP
. Также начиная с 5-й версии справка по конкретной команде может быть получена набором символов /?
после имени команды.
Например, набор команды:
C:\>ren /?
приведёт к получению справки по команде ren
:
Переименование одного или нескольких файлов. RENAME [диск:][путь]имя_файла1 имя_файла2. REN [диск:][путь]имя_файла1 имя_файла2. Для конечного файла нельзя указать другой диск или каталог.
Все команды DOS нечувствительны к регистру букв, то есть любая команда может быть набрана как строчными, так и заглавными буквами.
Создание текстовых файлов
Для этого в DOS используется команда . Формат команды:
где – имя диска, на котором будет сохранен созданный файл;
– путь до каталога, который будет содержать созданный файл;
– имя создаваемого файла.
Например, чтобы создать текстовый файл NAMETXT в каталоге CURS, в командной строке набирается
copy con CURS\NAME.TXT
После ввода этой команды требуется набрать текст файла и по окончании ввода нажать клавишу или (конец файла) и затем . На экране появится сообщение
Скопировано файлов: 1
Создайте в каталоге файл , набрав в качестве текста свои фамилию, имя и отчество. Просмотрите дерево каталога с файлами (рис. 2.10).
Рис. 2.10. Результат создания файла
. Команда COPY CON обладает ограниченными возможностями, поэтому для создания текстовых файлов обычно применяют специальные программы-редакторы. Например при использовании редактора Turbo Pascal необходимо в командной строке набрать путь к исполняемому файлу turbo.exe и нажать Enter. После набора текста (программы) его следует сохранить под требуемым именем в указанном каталоге и для возврата в DOS нажать Alt+X.
Просмотр содержимого файла
Для просмотра информации, содержащейся в файле, применяется команда .
Например, чтобы просмотреть содержимое файла NAME.TXT, в командной строке необходимо набрать
Просмотрите содержимое файла .
Для копирования содержимого файла с одного диска на другой или из одного каталога в другой применяется команда
где /v – режим копирования с проверкой соответствия копии оригиналу.
copy WIN\CURS\NAME.TXT WIN
Скопируйте файл в каталог под именем . Проверьте результат (рис. 2.11).
Рис. 2.11. Результат копирования файла
Объединение файлов
Объединение нескольких файлов можно осуществить с помощью команды и символа , соединяющего исходные файлы.
copy C:\TURBO\MYFILE\SORT.PAS+A:\XX\ROOTS.PAS A:\BVL.PAS
объединяет тексты программ SORT.PAS и ROOTS.PAS в один файл с именем BVL.PAS. Причем если все объединяемые файлы находятся в текущем каталоге и имя результирующего файла не указано, то ему присваивается имя первого файла.
D:\W\urok .txt D:\W\Q\urok1.txt
в файл . Проверьте результат командой , а затем командой (рис. 2.12).
Рис. 2.12. Результат объединения файлов
Переименование и перенос файлов
Эти процедуры производятся аналогично переименованию
в . Затем перенесите последний в каталог (рис. 2.13).
Рис. 2.13. Результат переименования и переноса файла
Вывод содержимого файла на печать
Содержимое файла можно вывести на печать двумя способами:
1) с помощью команды и параметра :
Например, C:\ >copy TURBO\MYFILE\BVL.PAS prn
2) с использованием команды . Формат команды:
Например, C:\TURBO\MYFILE>
После ввода этой команды на экране появляется запрос:
Для начала печати необходимо набрать .
Для удаления файлов используется команда . Формат команды:
из каталога .
, используя команду .
Работа с группами файлов
При копировании, объединении, переносе, удалении файлов, находящихся в одном каталоге, можно использовать
Соседние файлы в предмете Информатика
КомандыПравить
Вывод и изменение атрибутов файлов.
ATTRIB [+R | -R] [+A | -A ] [+S | -S] [+H | -H] [диск:] [путь] [имя_файла] [/S] [/D]
- + — установка атрибута;
- — — снятие атрибута;
- R — атрибут «Только чтение»;
- A — атрибут «Архивный»;
- S — атрибут «Системный»;
- H — атрибут «Скрытый»;
- [диск:] [путь] [имя_файла] — указание файла или набора файлов для обработки;
- /S — обработка файлов с указанными именами в текущей папке и во всех её подпапках;
- /D — обработка и файлов, и папок.
Эквивалентна команде UNIX chmod.
cd
или chdir
Вывод имени либо смена текущего каталога.
CHDIR [/D] [диск:][путь] CHDIR [..] CD [/D] [диск:][путь] CD [..]
где .. обозначает переход в родительский каталог.
Команда CD диск:
отображает имя текущего каталога указанного диска. Команда CD
без параметров отображает имена текущих диска и каталога. Параметр /D используется для одновременной смены текущих диска и каталога.
Изменение команды CHDIR
при включении расширенной обработки команд: имя текущего каталога в строке вызова преобразуется к тому же регистру символов, что и для существующих имен на диске. Так, команда CD C:\TEMP
на самом деле сделает текущим каталог C:\Temp
, если он существует на диске. Команда CHDIR
перестает рассматривать пробелы как разделители, что позволяет перейти в подкаталог, имя которого содержит пробелы, не заключая все имя каталога в кавычки. Например:
chdir \winnt\profiles\username\programs\start menu
приводит к тому же результату, что и:
cd "\winnt\profiles\username\programs\start menu"
При отключении расширенной обработки команд используется только второй вариант.
Эквивалентна команде Unix cd
(с параметрами) или pwd
(без параметров).
Команды для работы с каталогами
Набрав две точки (..) можно вернуться в предыдущий каталог; при вводе \ — в корневой каталог.
dir
— просмотр оглавления текущего каталога;dir *.exe
— выводится информация обо всех файлах с расширением EXE из текущего каталога;cd c:\catalog
— установить текущим каталог с именем catalog на диске C;cd[ ]..
— переход на каталог выше (пробелы необязательны);cd[ ]\
— переход в корневой каталог (пробелы необязательны);md books
— в текущем каталоге создать подкаталог books;md c:\archives
— в корневом каталоге на диске С: создается каталог archives;rd games
— удаление каталога games в текущем каталоге.
Выводит список файлов и подкаталогов, находящихся в заданном каталоге. Если команда задается без параметров, то выводится метка диска и его номер, имена файлов и каталогов (по одному на строку), включая расширения, а также дату и время их последней модификации. После этого выводится число файлов в каталоге, общий объём (в байтах), занимаемый файлами, и объём свободного пространства на диске.
DIR [диск:][маршрут][имя_файла] [/P] [/W] [A[[:]атрибуты]] [/O[[:]сортировка]] [/S] [/B] [/L] [/C]
- H — скрытые файлы;
- -H — нескрытые файлы;
- S — системные файлы;
- -S — файлы, отличные от системных;
- D — каталоги;
- -D — только файлы (не каталоги);
- A — файлы, готовые для архивизации;
- -A — файлы, не измененные после последней архивизации;
- R — файлы, доступные только по чтению;
- -R — файлы, не имеющие доступа только по чтению.
- N — сортировка по алфавиту (по имени);
- -N — в порядке, обратном алфавитному (Z—A);
- E — в алфавитном порядке по расширению;
- -E — по расширению в порядке, обратном порядке;
- D — по дате и времени (начиная с более ранних);
- -D — по дате и времени, начиная с поздних;
- S — по возрастанию размера;
- -S — по убыванию размера;
- C — по коэффициенту компрессии, начиная с меньшего;
- -C — по коэффициенту компрессии, начиная с большего.
О выводе структуры каталога или диска рассказывается в описании команды TREE, а о компрессированных дисках — в описании DBLSPACE. Для вывода подмножества файлов и каталогов вы можете использовать трафаретные символы (* и ?). Если задается более одного значения порядка сортировки, DIR сортирует файлы по первому критерию, затем по второму и т. д.
Можно переопределить набор параметров команды DIR, заданных с помощью переменной DIRCMD. Для этого используйте те же параметры, что и в командной строке DIR, но перед параметром нужно указывать также знак минуса, например, dir /-w. Используемые по умолчанию установки DIRCMD вы можете изменить также с помощью команды DOS SET, набрав их в командной строке после символа равенства (=). Новые установки будут действовать по умолчанию для всех последующих команд DIR до следующего использования SET DIRCMD в командной строке или перезапуска MS-DOS. Чтобы сбросить все назначенные по умолчанию параметры, наберите команду set dircmd=. Текущие установки переменной операционной среды DIRCMD вы можете просмотреть с помощью команды set. MS-DOS выводит на экран список параметров и их установок (подробности вы можете найти в описании SET).
Если есть необходимость использовать DIR для вывода одного листинга каталога за другим, пока не выведется содержимое каждого каталога текущего диска, и необходимо упорядочить каждый каталог по алфавиту, вывести его в широком формате и делать паузу после вывода каждого экрана — для этого, находясь в корневом каталоге, необходимость использовать команду dir /s/w/o/p. Чтобы при этом не выводились имена каталогов, следует использовать команду dir /s/w/o/p/ a: -d. Чтобы распечатать вывод, следует использовать символ переназначения: dir > prn.
Проверка диска и вывод отчета.
CHKDSK [том:[[путь]имя_файла]] [/F] [/V] [/R] [/X] [/I] [/C] [/L[:размер]]
том
— определяет точку подключения, имя тома или букву проверяемого диска с двоеточием;имя_файла
— Файлы, проверяемые на наличие фрагментации (только FAT/FAT32);/F
— исправление ошибок на диске;/V
— для FAT/FAT32: вывод полного пути и имени для каждого файла на этом диске. Для NTFS: также вывод сообщений об очистке;/R
— поиск поврежденных секторов и восстановление их содержимого (подразумевает/F
);/L:размер
— только для NTFS: изменение размера файла журнала до указанной величины (в КБ). Если размер не указан, выводится текущее значение размера;/X
— при необходимости предварительное отключение тома. Все открытые дескрипторы для этого тома будут недействительны (требует/F
);/I
— только для NTFS: менее строгая проверка индексных элементов;/C
— только для NTFS: пропуск проверки циклов внутри структуры папок.
Ключи /I
или /C
укорачивают время выполнения CHKDSK
за счет пропуска некоторых проверок тома.
Эквивалентна команде fsck
в Unix.
Также можно использовать команду scandisk
, которая ищет все повреждённые кластеры на диске.
Очищает компьютерный терминал.
Эквивалентна команде clear
в Unix.
Копирование одного или нескольких файлов в другое место.
COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/A | /B] источник [/A | /B] [+ источник [/A | /B] [[+ …]] [результат [/A | /B]]
источник
— имена одного или нескольких копируемых файлов;/A
— файл является текстовым файлом ASCII;/B
— файл является двоичным файлом;/D
— указывает на возможность создания зашифрованного файла;результат
— каталог и/или имя для конечных файлов;/V
— поверка правильности копирования файлов;/N
— использование, если возможно, коротких имен при копировании файлов, чьи имена не удовлетворяют стандарту 8.3;/Y
— подавление запроса подтверждения на перезапись существующего конечного файла;/-Y
— обязательный запрос подтверждения на перезапись существующего конечного файла;/Z
— копирование сетевых файлов с возобновлением.
Ключ /Y
можно установить через переменную среды COPYCMD
. Ключ /-Y
командной строки переопределяет такую установку. По умолчанию требуется подтверждение, если только команда COPY
не выполняется в пакетном файле. При вводе вместо имени конечного файла атрибута con, содержимое копируемого файла отображалось на экране. Возможны и другие вариации команды COPY с атрибутом con, обозначающим устройства ввода-вывода. При выполнении команды COPY происходит копирование символов (байтов) из исходного файла по-одному до достижения символа окончания файла. В случае если такой символ встречается в середине файла, при выполнении команды COPY, файл копируется не полностью.
Эквивалентна команде cp
в Unix. Расширенными возможностями обладают XCOPY
и robocopy
Удаление одного или нескольких файлов.
DEL [/P] [/F] [/S] [/Q] [/A[[:]атрибуты]] имена ERASE [/P] [/F] [/S] [/Q] [/A[[:]атрибуты]] имена
имена
— имена одного или нескольких файлов. Для удаления сразу нескольких файлов используются подстановочные знаки. Если указан каталог, из него будут удалены все файлы;/P
— запрос на подтверждение перед удалением каждого файла;/F
— принудительное удаление файлов, доступных только для чтения;/S
— удаление указанных файлов из всех подкаталогов;/Q
— отключение запроса на подтверждение при удалении файлов;/A
— отбор файлов для удаления по атрибутам;атрибуты
— отбор файлов для удаления по атрибутам:
S
— системные файлы;R
— доступные только для чтения;H
— скрытые файлы;A
— файлы для архивирования.
Префикс «-
» имеет значение НЕ.
Изменение команд DEL
и ERASE
при включении расширенной обработки команд. Результаты вывода для ключа /S
принимают обратный характер, то есть выводятся только имена удаленных файлов, а не файлов, которые не удалось найти.
Эквивалентна команде rm
в Unix.
Удаление каталога вместе с файлами и подкаталогами.
deltree [/y] каталог
В Unix функциональность deltree
предоставляется командой rm
с параметром -r
.
Вывод списка файлов и подкаталогов из указанного каталога.
DIR [диск:][путь][имя_файла] [/A[[:]атрибуты]] [/B] [/C] [/D] [/L] [/N] [/O[[:]порядок]] [/P] [/Q] [/S] [/T[[:]время]] [/W] [/X] [/4]
- [диск:][путь][имя_файла] — диск, каталог и/или файлы, которые следует включить в список;
- /A — вывод файлов с указанными атрибутами: D — каталоги; R — доступные только для чтения; H — скрытые файлы; A — файлы для архивирования; S — системные файлы; префикс «-» имеет значение НЕ;
- /B — вывод только имен файлов;
- /C — применение разделителя групп разрядов для вывода размеров файлов (по умолчанию). Для отключения этого режима служит ключ /-C;
- /D — вывод списка в несколько столбцов с сортировкой по столбцам;
- /L — использование нижнего регистра для имен файлов;
- /N — отображение имен файлов в крайнем правом столбце;
- /O — сортировка списка отображаемых файлов: N — по имени (алфавитная); S — по размеру (сперва меньшие); E — по расширению (алфавитная); D — по дате (сперва более старые); G — начать список с каталогов; префикс «-» обращает порядок;
- /P — пауза после заполнения каждого экрана;
- /Q — вывод сведений о владельце файла;
- /S — вывод списка файлов из указанного каталога и его подкаталогов;
- /T — выбор поля времени для отображения и сортировки время: C — создание; A — последнее использование; W — последнее изменение;
- /W — вывод списка в несколько столбцов;
- /X — отображение коротких имен для файлов, чьи имена не соответствуют стандарту 8.3. Формат аналогичен выводу с ключом /N, но короткие имена файлов выводятся слева от длинных. Если короткого имени у файла нет, вместо него выводятся пробелы;
- /4 — вывод номера года в четырёхзначном формате.
Стандартный набор ключей можно записать в переменную среды DIRCMD. Для отмены их действия следует ввести в команде те же ключи с префиксом «-», например: /-W.
Эквивалентна команде ls
в unix.
Вывод информации в любой источник назначения, файл, экран и т. д.
echo shutdown /p /t 3600 >> C:\\autoend.bat
Функции данной команды и форма записи для Windows и Unix — разные.
Отображает сообщение (message) или включает и выключает эхо-отображение команд.
ECHO[ ][ON|OFF] ECHO[ ][message]
Изменение MBR, а именно восстановление главной загрузочной записи, если она оказалась повреждена/модифицирована/затёрта. Запуск команды без аргументов вызывает меню для создания, удаления, и получения информации о разделах диска. Также может быть сменён активный (загрузочный) раздел.
FORMAT том: [/FS:система] [/V:метка] [/Q] [/A:размер] [/C] [/X] FORMAT том: [/V:метка] [/Q] [/F:размер] FORMAT тома: [/V:метка] [/Q] [/T:дорожки /N:секторы] FORMAT тома: [/V:метка] [/Q] FORMAT том: [/Q]
- том — указывает букву диска (с последующим двоеточием), точку подключения или имя тома;
- /FS:filesystem — указывает тип файловой системы (FAT, FAT32 или NTFS);
- /V:метка — метка тома;
- /Q — быстрое форматирование;
- /C — только для NTFS: установка режима сжатия по умолчанию для всех файлов, создаваемых на новом томе;
- /X — инициирует отключение тома, в качестве первого действия, если это необходимо. Все открытые дескрипторы тома будут неверны.
- /S — копирует на диск минимальный набор системных файлов, необходимых для загрузки MS-DOS с этого диска (io.sys, msdos.sys, drvspace.bin, command.com);
- /A:размер — заменяет размер кластера по умолчанию. В общих случаях рекомендуется использовать размеры кластера по умолчанию;
- /F:размер — указывает размер форматируемых гибких дисков;
- /T:дорожки — число дорожек на каждой стороне диска;
- /N:секторы — число секторов на каждой дорожке.
How to Display the Status of Transmissions for Packets of a Specific Address Type
Use the -f option of the netstat command to view statistics related to
packet transmissions of a particular address family.
- View statistics for transmissions of either IPv4 or IPv6 packets.
$ netstat -f inet | inet6
To view IPv4 transmission information, type inet as the argument to netstat -f. Use
inet6 as the argument to netstat -f to view IPv6 information.
Example 8-10 Status of IPv4 Packet Transmission
TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ------- host58.734 host19.nfsd 49640 0 49640 0 ESTABLISHED host58.38063 host19.32782 49640 0 49640 0 CLOSE_WAIT host58.38146 host41.43601 49640 0 49640 0 ESTABLISHED host58.996 remote-host.login 49640 0 49206 0 ESTABLISHED
Example 8-11 Status of IPv6 Packet Transmission
TCP: IPv6 Local Address Remote Address Swind Send-Q Rwind Recv-Q State If ------------------ ------------------------- ----- ------ ----- ------ --------- ----- localhost.38065 localhost.32792 49152 0 49152 0 ESTABLISHED localhost.32792 localhost.38065 49152 0 49152 0 ESTABLISHED localhost.38089 localhost.38057 49152 0 49152 0 ESTABLISHED
How to Display the Status of Sockets
The -a option of the netstat command enables you to view the status
of sockets on the local host.
- Type the following to display the status of sockets and routing table entries:
% netstat -a
Example 8-9 Displaying All Sockets and Routing Table Entries
UDP: IPv4 Local Address Remote Address State -------------------- -------------------- ------- *.bootpc Idle host85.bootpc Idle *.* Unbound *.* Unbound *.sunrpc Idle *.* Unbound *.32771 Idle *.sunrpc Idle *.* Unbound *.32775 Idle *.time Idle . . *.daytime Idle *.echo Idle *.discard Idle UDP: IPv6 Local Address Remote Address State If --------------------------------- --------------------------------- ---------- ----- *.* Unbound *.* Unbound *.sunrpc Idle *.* Unbound *.32771 Idle *.32778 Idle *.syslog Idle . . TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State -------------------- -------------------- ----- ------ ----- ------ ------- *.* *.* 0 0 49152 0 IDLE localhost.4999 *.* 0 0 49152 0 LISTEN *.sunrpc *.* 0 0 49152 0 LISTEN *.* *.* 0 0 49152 0 IDLE *.sunrpc *.* 0 0 49152 0 LISTEN . . *.printer *.* 0 0 49152 0 LISTEN *.time *.* 0 0 49152 0 LISTEN *.daytime *.* 0 0 49152 0 LISTEN *.echo *.* 0 0 49152 0 LISTEN *.discard *.* 0 0 49152 0 LISTEN *.chargen *.* 0 0 49152 0 LISTEN *.shell *.* 0 0 49152 0 LISTEN *.shell *.* 0 0 49152 0 LISTEN *.kshell *.* 0 0 49152 0 LISTEN *.login . . *.* 0 0 49152 0 LISTEN *TCP: IPv6 Local Address Remote Address Swind Send-Q Rwind Recv-Q State If ----------------------- ----------------------- ----- ------ ----- ------ ---- *.* *.* 0 0 49152 0 IDLE *.sunrpc *.* 0 0 49152 0 LISTEN *.* *.* 0 0 49152 0 IDLE *.32774 *.* 0 0 49152
ПримечанияПравить
- Параметр в виде P>1.txt позволит записать полученные данные в файл с именем 1.txt. Имя файла можно задать любое.
How to Display Statistics by Protocol
The netstat -s option displays protocol statistics for the UDP, TCP, SCTP, ICMP,
and IP protocols.
- Display the protocol status.
$ netstat -s
Example 8-5 Network Protocol Statistics
RAWIP rawipInDatagrams = 4701 rawipInErrors = 0 rawipInCksumErrs = 0 rawipOutDatagrams = 4 rawipOutErrors = 0 UDP udpInDatagrams = 10091 udpInErrors = 0 udpOutDatagrams = 15772 udpOutErrors = 0 TCP tcpRtoAlgorithm = 4 tcpRtoMin = 400 tcpRtoMax = 60000 tcpMaxConn = -1 . . tcpListenDrop = 0 tcpListenDropQ0 = 0 tcpHalfOpenDrop = 0 tcpOutSackRetrans = 0 IPv4 ipForwarding = 2 ipDefaultTTL = 255 ipInReceives =300182 ipInHdrErrors = 0 ipInAddrErrors = 0 ipInCksumErrs = 0 . . ipsecInFailed = 0 ipInIPv6 = 0 ipOutIPv6 = 3 ipOutSwitchIPv6 = 0 IPv6 ipv6Forwarding = 2 ipv6DefaultHopLimit = 255 ipv6InReceives = 13986 ipv6InHdrErrors = 0 ipv6InTooBigErrors = 0 ipv6InNoRoutes = 0 . . rawipInOverflows = 0 ipv6InIPv4 = 0 ipv6OutIPv4 = 0 ipv6OutSwitchIPv4 = 0 ICMPv4 icmpInMsgs = 43593 icmpInErrors = 0 icmpInCksumErrs = 0 icmpInUnknowns = 0 . . icmpInOverflows = 0 ICMPv6 icmp6InMsgs = 13612 icmp6InErrors = 0 icmp6InDestUnreachs = 0 icmp6InAdminProhibs = 0 . . icmp6OutGroupQueries= 0 icmp6OutGroupResps = 2 icmp6OutGroupReds = 0 IGMP: 12287 messages received 0 messages received with too few bytes 0 messages received with bad checksum 12287 membership queries received SCTP sctpRtoAlgorithm = vanj sctpRtoMin = 1000 sctpRtoMax = 60000 sctpRtoInitial = 3000 sctpTimHearBeatProbe = 2 sctpTimHearBeatDrop = 0 sctpListenDrop = 0 sctpInClosed = 0
How to Display the Status of Transport Protocols
You can display the status of the transport protocols through the netstat
command. For detailed information, refer to the netstat(1M) man page.
- Display the status of the TCP and SCTP transport protocols on a system.
$ netstat
- Display the status of a particular transport protocol on a system.
$ netstat -P transport-protocol
Values for the transport-protocol variable are tcp, sctp, or udp.
Example 8-6 Displaying the Status of the TCP and SCTP Transport Protocols
This example shows the output of the basic netstat command. Note that IPv4-only
information is displayed.
$ netstat TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State ----------------- -------------------- ----- ------ ----- ------ ------- lhost-1.login abc.def.local.Sun.COM.980 49640 0 49640 0 ESTABLISHED lhost-1.login ghi.jkl.local.Sun.COM.1020 49640 1 49640 0 ESTABLISHED remhost-1.1014 mno.pqr.remote.Sun.COM.nfsd 49640 0 49640 0 TIME_WAIT SCTP: Local Address Remote Address Swind Send-Q Rwind Recv-Q StrsI/O State ---------------- -------------- ----- ------ ------ ------ ------ ------- *.echo 0.0.0.0 0 0 102400 0 128/1 LISTEN *.discard 0.0.0.0 0 0 102400 0 128/1 LISTEN *.9001 0.0.0.0 0 0 102400 0 128/1 LISTEN
Example 8-7 Displaying the Status of a Particular Transport Protocol
This example shows the results when you specify the -P option of netstat.
$ netstat -P tcp TCP: IPv4 Local Address Remote Address Swind Send-Q Rwind Recv-Q State ----------------- -------------------- ----- ------ ----- ------ ------- lhost-1.login abc.def.local.Sun.COM.980 49640 0 49640 0 ESTABLISHED lhost.login ghi.jkl.local.Sun.COM.1020 49640 1 49640 0 ESTABLISHED remhost.1014 mno.pqr.remote.Sun.COM.nfsd 49640 0 49640 0 TIME_WAIT TCP: IPv6 Local Address Remote Address Swind Send-Q Rwind Recv-Q State If ---------------- ---------------------- ------ ----- ------ ----------- ----- localhost.38983 localhost.32777 49152 0 49152 0 ESTABLISHED localhost.32777 localhost.38983 49152 0 49152 0 ESTABLISHED localhost.38986 localhost.38980 49152 0 49152 0 ESTABLISHED
How to Display Network Interface Status
The i option of the netstat command shows the state of the network
interfaces that are configured on the local system. With this option, you can
determine the number of packets a system transmits and receives on each network.
- Display the status of interfaces on the network.
$ netstat -i
Example 8-8 Network Interface Status Display
The next example shows the status of IPv4 and IPv6 packet flow
through the host’s interfaces.
For example, the input packet count (Ipkts) that is displayed for a server
can increase each time a client tries to boot, while the output packet
count (Opkts) remains steady. This outcome suggests that the server is seeing the
boot request packets from the client. However, the server does not know to
respond to them. This confusion might be caused by an incorrect address in
the hosts, ipnodes, or ethers database.
However, if the input packet count is steady over time, then the
machine does not see the packets at all. This outcome suggests a different
type of failure, possibly a hardware problem.
Name Mtu Net/Dest Address Ipkts Ierrs Opkts Oerrs Collis Queue lo0 8232 loopback localhost 142 0 142 0 0 0 hme0 1500 host58 host58 1106302 0 52419 0 0 0 Name Mtu Net/Dest Address Ipkts Ierrs Opkts Oerrs Collis lo0 8252 localhost localhost 142 0 142 0 0 hme0 1500 fe80::a00:20ff:feb9:4c54/10 fe80::a00:20ff:feb9:4c54 1106305 0 52422 0 0
ТакжеПравить
Netstat(8)
Name
netstat – show network status
Synopsis
netstat [-uanvkRL] [-f address_family] [-P protocol]
netstat -g [-nv] [-f address_family]
netstat -p [-n] [-f address_family]
netstat -s [-a] [-f address_family] [-P protocol] [-T u | d ] [interval [count]]
netstat -m [-T u | d ] [-v] [interval [count]]
netstat -i [-I interface] [-an] [-f address_family] [-T u | d ] [interval [count]]
netstat -r [-anvR] [-f address_family | filter]
netstat -M [-ns] [-f address_family]
netstat -D [-I interface] [-f address_family]
netstat -d [-f address_family]
Description
The netstat command displays the contents of certain network-related data structures in various formats, depending on the options you select.
The first form of the command (with no required arguments) displays a list of active sockets for each protocol.
The second, third, and fourth forms (–g, –p, and –s options) display information from various network data structures.
The fifth form (–m option) displays STREAMS memory statistics.
The sixth form (–i option) shows the state of the interfaces.
The seventh form (–r option) displays the routing table.
The eighth form (–M option) displays the multicast routing table.
The ninth form (–D option) displays the state of DHCP on one or all interfaces.
The tenth form (–d option) displays the table of destination cache entries.
These forms are described in greater detail below.
With no arguments (the first form), netstat displays connected sockets for PF_INET, PF_INET6, and PF_UNIX, unless modified otherwise by the –f option.
Options
- –a
Show the state of all sockets, all routing table entries, or all interfaces, both physical and logical. Normally, listener sockets used by server processes are not shown. Under most conditions, only interface, host, network, and default routes are shown and only the status of physical
interfaces is shown.- –d
Show the destination cache entry table. See DISPLAYS, below.
- –f address_family
- inet
For the AF_INET address family showing IPv4 information.
- inet6
For the AF_INET6 address family showing IPv6 information.
- unix
For the AF_UNIX address family.
- sdp
netstat–f
inetinet6–P
sdpto get SDP
information.- Local Address
Local IP address
- Remote Address
Remote IP address
- State
Current state of the socket
- RxBPending
- TxBQueued
Bytes queued for Tx (includes TxBPosted)
- TxBPosted
Bytes sent to HW for transmission
- LAdvtSz
Local advertised buffer size
- RAdvtSz
Remote advertised buffer size
- LAdvtBuff
Number of local advertised Rx buffers
- RAdvtBuff
Number of remote advertised Rx buffers
- LPostBuff
Number of Rx buffers currently posted
- –f filter
With –r only, limit the display of routes to those matching the specified filter. A filter rule consists of a keyword:value pair. The known keywords and the value syntax are:
- af:{inet|inet6|unix|sdp|number}
Selects an address family. This is identical to –f address_family and both syntaxes are supported.
- outif:{name|ifIndex|any|none}
Selects an output interface. You can specify the interface by name (such as hme0) or by ifIndex number (for example, 2). If any is used, the filter matches all routes having a specified interface (anything
other than null). If none is used, the filter matches all routes having a null interface. Note that you can view the index number (ifIndex) for an interface with the –a option of ifconfig(8).- dst:{ip-address[/mask]|any|none}
Selects a destination IP address. If specified with a mask length, then any routes with matching or longer (more specific) masks are selected. If any is used, then all but addresses but 0 are selected. If none is used, then address 0 is selected.
- flags:[+ -]?[ABDGHLMSU]+
Selects routes tagged with the specified flags. By default, the flags as specified must be set in order to match. With a leading +, the flags specified must be set but others are ignored. With a leading -, the flags specified must not be set
and others are permitted.
You can specify multiple instances of –f to specify multiple filters. For example:
% netstat -nr -f outif:hme0 -f outif:hme1 -f dst:10.0.0.0/8
The preceding command displays routes within network 10.0.0.0/8, with mask length 8 or greater, and an output interface of either hme0 or hme1, and excludes all other routes.
- –g
Show the multicast group memberships for all interfaces. If the –v option is included, source-specific membership information is also displayed. See DISPLAYS, below.
- –i
Show the state of the interfaces that are used for IP traffic. Normally this shows statistics for the physical interfaces. When combined with the –a option, this will also report information for the logical interfaces. See ifconfig(8).
- k
Show only sockets which have kernel data path bypass capability
enabled.- –m
Show the STREAMS memory statistics.
- –n
Show network addresses as numbers. netstat normally displays addresses as symbols. This option may be used with any of the display formats.
- –p
Show the net to media tables. See DISPLAYS, below.
- –r
Show the routing tables. Normally, only interface, host, network, and default routes are shown, but when this option is combined with the –a option, all routes will be displayed, including cache. If you have not set up a multicast route, –ra might
not show any multicast routing entries, although the kernel will derive such an entry if needed.- –s
Show per-protocol statistics. When used with the –M option, show multicast routing statistics instead. When used with the –a option, per-interface statistics will be displayed, when available, in addition to statistics global to the system. See DISPLAYS,
below.- –T u | d
Display a time stamp.
Specify u for a printed representation of the internal representation of time. See time(2). Specify d for standard date
format. See date(1).- –u
- –v
Verbose. Show additional information for the sockets, STREAMS memory statistics, routing
table, processes, and multicast group memberships.- –I interface
Show the state of a particular interface. interface can be any valid interface such as hme0 or eri0. Normally, the status and statistics for physical interfaces are displayed.
When this option is combined with the –a option,
information for the logical interfaces is also reported.- –M
Show the multicast routing tables. When used with the –s option, show multicast routing statistics instead.
- –P protocol
Limit display of statistics or state of all sockets to those applicable to
protocol. The protocol can be one of
icmpv6, icmp,
ip, ipv6, sctp,
igmp, udp,
tcp, sdp,
rawip. rawip can also be
specified as raw. The command accepts protocol
options only as all lowercase.- –L
- –D
Show the status of DHCP configured interfaces.
- –R
This modifier displays extended security attributes for sockets and routing table entries. The –R modifier is available only if the system is configured with the Solaris Trusted Extensions feature.
When displaying socket information using the first form of the command, this option displays additional information for Multi-Level Port (MLP) sockets. This includes:
The label for the peer if the socket is connected.
- P
The socket is a MLP on zone-private IP addresses.
- S
Operands
- interval
Display statistics accumulated since last display every interval seconds, repeating forever, unless count is specified. When invoked with interval, the first row of netstat output shows statistics
accumulated since last reboot.- count
Display interface statistics the number of times specified by count, at the interval specified by interval.
DISPLAYS
Active Sockets (First Form)
The display for each active socket shows the local and remote address, the send and receive queue sizes (in bytes), the send and receive windows (in bytes), and the internal state of the protocol.
For udp sockets, the display will be:
The local and remote IP address
The send and receive buffer size (in bytes)
The number of times overflow occurred for transmitting/receiving
packetsThe internal state of the protocol
The symbolic format normally used to display socket addresses is either:
hostname.port
when the name of the host is specified, or
network.port
if a socket address specifies a network but no specific host.
The numeric host address or network number associated with the socket is used to look up the corresponding symbolic hostname or network name in the hosts or networks database.
For SCTP sockets, because an endpoint can be represented by multiple addresses, the verbose option (–v) displays the list of all the local and remote addresses.
TCP Sockets
- BOUND
Bound, ready to connect or listen.
- CLOSED
Closed. The socket is not being used.
- CLOSING
Closed, then remote shutdown; awaiting acknowledgment.
- CLOSE_WAIT
Remote shutdown; waiting for the socket to close.
- ESTABLISHED
Connection has been established.
- FIN_WAIT_1
Socket closed; shutting down connection.
- FIN_WAIT_2
Socket closed; waiting for shutdown from remote.
- IDLE
Idle, opened but not bound.
- LAST_ACK
Remote shutdown, then closed; awaiting acknowledgment.
- LISTEN
Listening for incoming connections.
- SYN_RECEIVED
Initial synchronization of the connection under way.
- SYN_SENT
Actively trying to establish connection.
- TIME_WAIT
Wait after close for remote shutdown retransmission.
SCTP Sockets
- CLOSED
Closed. The socket is not being used.
- LISTEN
Listening for incoming associations.
- ESTABLISHED
Association has been established.
- COOKIE_WAIT
INIT has been sent to the peer, awaiting acknowledgment.
- COOKIE_ECHOED
State cookie from the INIT-ACK has been sent to the peer, awaiting acknowledgment.
- SHUTDOWN_PENDING
SHUTDOWN has been received from the upper layer, awaiting acknowledgment of all outstanding DATA from the peer.
- SHUTDOWN_SENT
All outstanding data has been acknowledged in the SHUTDOWN_SENT state. SHUTDOWN has been sent to the peer, awaiting acknowledgment.
- SHUTDOWN_RECEIVED
SHUTDOWN has been received from the peer, awaiting acknowledgment of all outstanding DATA.
- SHUTDOWN_ACK_SENT
All outstanding data has been acknowledged in the SHUTDOWN_RECEIVED state. SHUTDOWN_ACK has been sent to the peer.
Network Data Structures (Second Through Fifth Forms)
The form of the display depends upon which of the –g, –m, –p, or –s options you select.
- –g
Displays the list of multicast group membership.
- –m
Displays the memory usage, for example, STREAMS mblks.
- –p
Displays the net to media mapping table. For IPv4, the address resolution table is displayed. See arp(8). For IPv6, the neighbor cache is displayed.
- –s
Displays the statistics for the various protocol layers.
The statistics use the MIB specified variables. The defined values for ipForwarding are:
- forwarding(1)
Acting as a gateway.
- not-forwarding(2)
Not acting as a gateway.
The IPv4, IPv6 and ICMPv6 protocol layers maintain per-interface statistics. If the
–a option is specified with the –s option, then the per-interface
statistics as well as the total sums are displayed. Otherwise, just the sum of the statistics are
shown.
For the second, third, and fourth forms of the command, you must specify at least –g, –p, or –s. You can specify any combination of these options. You can also specify –m (the fifth form) with any set of the –g,
–p, and –s options. If you specify more than one of these options, netstat displays the information for each one of them.
Interface Status (Sixth Form)
The interface status display lists information for all current interfaces, one interface per line. If an interface is specified using the –I option, it displays information for only the specified interface.
The list consists of the interface name, mtu (maximum transmission unit, or maximum packet size)(see ifconfig(8)), the network to
which the interface is attached, addresses for each interface, and counter associated with the interface. The counters show the number of input packets, input errors, output packets, output errors, and collisions, respectively. For Point-to-Point interfaces, the Net/Dest field is the name or address
on the other side of the link.
If the –a option is specified with either the –i option or the –I option, then the output includes names of the physical interface(s), counts for input packets and output packets for each logical interface, plus additional information.
If the –n option is specified, the list displays the IP address instead of the interface name.
input eri0 output input (Total) output packets errs packets errs colls packets errs packets errs colls 227681 0 659471 1 502 261331 0 99597 1 502 10 0 0 0 0 10 0 0 0 0 8 0 0 0 0 8 0 0 0 0 10 0 2 0 0 10 0 2 0 0
If the input interface is not specified, the first interface of address family inet or inet6 will be displayed.
Routing Table (Seventh Form)
- U
Indicates route is up.
- G
Route is to a gateway.
- H
Route is to a host and not a network.
- M
Redundant route established with the –multirt option.
- S
Route was established using the –setsrc option.
- D
Route was created dynamically by a redirect.
- B
Packets will be silently dropped (RTF_BLACKHOLE set).
- R
Packets will be dropped with ICMP error sent (RTF_REJECT set).
- I
Indirect routes (gateway not directly reachable) established with the –indirect option.
- Z
(non-global exclusive-IP zone only) The route was statically added on boot based on routing information configured using zonecfg(8) in the
global zone.
- b
- C
Clones interface host route entries for on-link destinations.
- L
Local addresses for the host.
Interface routes are created for each interface attached to the local host; the gateway field for such entries shows the address of the outgoing interface.
The use column displays the number of packets sent or forwarded using the route in question.
The interface entry indicates the network interface utilized for the route.
Multicast Routing Tables (Eighth Form)
The multicast routing table consists of the virtual interface table and the actual routing table.
DHCP Interface Information (Ninth Form)
The DHCP interface information consists of the interface name, its current state, lease information, packet counts, and a list of flags.
The states correlate with the specifications set forth in RFC 2131.
Lease information includes:
when the lease began;
when lease renewal will begin; and
when the lease will expire.
The flags currently defined include:
- BOOTP
The interface has a lease obtained through BOOTP (IPv4 only).
- BUSY
The interface is busy with a DHCP transaction.
- PRIMARY
The interface is the primary interface. See dhcpinfo(1) and ifconfig(8).
- FAILED
The interface is in failure state and must be manually restarted.
Packet counts are maintained for the number of packets sent, the number of packets received, and the number of lease offers declined by the DHCP client. All three counters are initialized to zero and then incremented while obtaining a lease. The counters are reset when
the period of lease renewal begins for the interface. Thus, the counters represent either the number of packets sent, received, and declined while obtaining the current lease, or the number of packets sent, received, and declined while attempting to obtain a future lease.
Destination Cache Entry Table (Tenth Form)
The destination cache entry display shows the recorded path MTU, the age (in seconds) of the entry, and flags. The P flag indicates that a path MTU is recorded. The S flag indicates that the path MTU is smaller than the minimum that IP will allow. The
U flag indicates that some transport metrics (round-trip time, and so forth) are cached in the destination cache entry.
Files
- /etc/default/inet_type
Attributes
See Also
dhcpinfo(1), net_kernel_bypass(3LIB), kstat(4D), inet(4P), inet6(4P), hosts(5), inet_type(5), networks(5), protocols(5), services(5), attributes(7), dhcp(7), arp(8), dhcpagent(8), ifconfig(8), iostat(8), kstat(8), savecore(8), vmstat(8), zonecfg(8)
Droms, R., RFC 2131, Dynamic Host Configuration Protocol, Network Working Group, March 1997.
Droms, R. RFC 3315, Dynamic Host Configuration Protocol for IPv6 (DHCPv6). Cisco Systems. July 2003.
Notes
When displaying interface information, netstat honors the DEFAULT_IP setting in /etc/default/inet_type. If it is set to IP_VERSION4, then netstat will omit information relating to IPv6 interfaces,
statistics, connections, routes and the like.
However, you can override the DEFAULT_IP setting in /etc/default/inet_type on the command-line. For example, if you have used the command-line to explicitly request IPv6 information by using the inet6 address family or one of the
IPv6 protocols, it will override the DEFAULT_IP setting.
The netstat utility obtains TCP statistics from the system by opening /dev/tcp and issuing queries. Because of this, netstat might display an extra, unused connection in IDLE state when reporting connection status.
How to Display the Status of Known Routes
- Display the IP routing table.
$ netstat -r
Example 8-12 Routing Table Output by the netstat Command
Routing Table: IPv4 Destination Gateway Flags Ref Use Interface -------------------- -------------------- ----- ----- ------ --------- host15 myhost U 1 31059 hme0 10.0.0.14 myhost U 1 0 hme0 default distantrouter UG 1 2 hme0 localhost localhost UH 42019361 lo0 Routing Table: IPv6 Destination/Mask Gateway Flags Ref Use If --------------------------- --------------------------- ----- --- ------ ----- 2002:0a00:3010:2::/64 2002:0a00:3010:2:1b2b:3c4c:5e6e:abcd U 1 0 hme0:1 fe80::/10 fe80::1a2b:3c4d:5e6f:12a2 U 1 23 hme0 ff00::/8 fe80::1a2b:3c4d:5e6f:12a2 U 1 0 hme0 default fe80::1a2b:3c4d:5e6f:12a2 UG 1 0 hme0 localhost localhost UH 9 21832 lo0