Netstat is used to display active TCP connections and related listening ports in the computer or system. Actually, there are more features provided by netstat like display statistics about network stack protocols, IPv4, IPv6, TCP, UDP, etc.
Описание команды NETSTAT
Netstat – это утилита командной строки Windows выводящая на дисплей состояние TCP-соединений. Команда netstat отображает статистику активных подключений TCP, портов, прослушиваемых компьютером, статистики Ethernet, таблицы маршрутизации IP, статистики IPv4 (для протоколов IP, ICMP, TCP и UDP) и IPv6 (для протоколов IPv6, ICMPv6, TCP через IPv6 и UDP через IPv6). Запущенная без параметров, команда netstat отображает подключения TCP.
Windows 10 netstart commands (Image credit: Windows Central)
On Windows 10, netstat (network statistics) has been around for a long time, and it’s a command-line tool that you can use in Command Prompt to display statistics for all network connections. It allows you to understand open and connected ports to monitor and troubleshoot networking problems for system or applications.
When using this tool, you can list active networks (incoming and outgoing) connections and listening ports. You can view network adapter statistics as well as statistics for protocols (such as IPv4 and IPv6). You can even display the current routing table, and much more.
In this Windows 10 guide, we’ll walk you through the steps to use the netstat command to examine connections to discover open and connected network ports.
I’ve recently been given a chance to write a simple tcp-client for a project of mine, and due to my huge ignorance with tcp/ip, I have a hard time getting it to work properly.
I find that sometimes I can get weird connection issue when the connection refused as the tcp server is down or sometimes I might get an exception when calling receive.
As the tcp-server is a black box and we have no access to it, I’m wondering in this situation, what’s the best way to write unit tests for this?
I’m thinking either I should write a tcp-server and make it return certain inputs as what I would expect from the real server or just mock the functions related to return ideal situation data.
I just don’t like the fact that sometimes I might get weird connection/receive issue and I would like to know how to properly write unit test which I can reuse/extend in the future to ensure that everything that work before should still be working in case my code or their code change.
13 gold badges71 silver badges104 bronze badges
asked Nov 8, 2011 at 1:49
You should have two kinds of tests:
Integration tests – with real bare-bone TCP server that can send and receive connections. Create this server that has the bare minimum functionality and use it to test how your client behaves. Using a simple TCP server you can test how your client send and receive messages and how it connects and disconnect from the server. Another useful test is how several clients connect and send messages to the server.
Unit tests – using Mocking you can test more complex scenarios. You won’t be able to send or receive messages but you can test the client’s internal logic – how it behaves if two messages with arrive, re-sending in case of errors etc.
Using both kinds of tests you should be able to cover most of your client’s functioanlity
answered Nov 10, 2011 at 7:18
Dror Helper
15 gold badges80 silver badges129 bronze badges
For unit testing, I’d create a simple socket server (kicked off when the UT starts) just for the purpose of testing the client. If you make it simple and standalone you’ll reduce hassles running the test. You may also be able to use tools like ncat to facilitate this.
However having said that there may be problems that might be harder for the UT to pick up. Keepalive issues, maybe external problems such as routing. But if you use a real listening socket (as opposed to mocking a connection) it’s real TCP.
answered Nov 8, 2011 at 4:11
1 gold badge24 silver badges37 bronze badges
I’m writing a TCP/IP client and I would need a “test server” to be able to test easily. It should listen on a configurable port, show me when a client connects, and what the client sent. It should allow me to manually enter text to send back to the client.
It should work on Windows.
Does anyone use another tool to test socket connections and is happy with it?
asked Feb 5, 2009 at 10:30
Hercules is fantastic. It’s a fully functioning tcp/udp client/server, amazing for debugging sockets. More details on the web site.
answered Feb 5, 2009 at 21:44
3 gold badges28 silver badges36 bronze badges
netcat (nc.exe) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as “OK” in your antivirus software (how you do this will depend on what type of antivirus software you use).
answered Feb 5, 2009 at 10:39
10 gold badges105 silver badges169 bronze badges
Try Wireshark or WebScarab second is better for interpolating data into the exchange (not sure Wireshark even can). Anyway, one of them should be able to help you out.
answered Feb 5, 2009 at 10:36
I would go with netcat too , but since you can’t use it , here is an alternative : netcat :). You can find netcat implemented in three languages ( python/ruby/perl ) . All you need to do is install the interpreters for the language you choose . Surely , that won’t be viewed as a hacking tool .
Here are the links :
answered Feb 5, 2009 at 11:22
117 gold badges344 silver badges516 bronze badges
In situations like this, why not write your own? A simple server app to test connections can be done in a matter of minutes if you know what you’re doing, and you can make it respond exactly how you need to, and for specific scenarios.
answered Feb 5, 2009 at 21:48
David Anderson
5 gold badges50 silver badges76 bronze badges
Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It’s not directly a test server. It is placed in-between a client and a server but allow to see what is going through the “tube” and also to change what is going through.
answered Feb 9, 2009 at 9:25
4 gold badges30 silver badges34 bronze badges
TL;DR
Tool to test concurrent connections towards a server listening to a TCP port
Description
Given a hostname, port, the number of connections (100 by default), a delay between connections (10ms by default) and an interval between stats updates to the standard output…
It will use goroutines to open TCP connections and try to read from them
The tool will exit once all connections have been dialed (successfully or not)
Exit status different from 0 represent executions where all connections were not established successfully, facilitating the integration in test suites.
Usage
Execution using Docker
See our public docker image and its documentation. The image is being updated continuously; you can bind to specific versions, or to the “latest” tag.
Installation
% go get github.com/dachad/tcpgoon
Help
<div dir="auto" data-snippet-clipboard-copy-content="% tcpgoon –help tcpgoon tests concurrent connections towards a server listening on a TCP port
Usage: tcpgoon [command]
Available Commands: help Help about any command run Run tcpgoon test version Show tcpgoon version
Flags: -h, –help help for tcpgoon
Use "tcpgoon [command] –help" for more information about a command. % tcpgoon run –help Run tcpgoon test
Usage: tcpgoon run [flags]
Flags: -y, –assume-yes Force execution without asking for confirmation -c, –connections int Number of connections you want to open (default 100) -d, –debug Print debugging information to the standard error -t, –dial-timeout int Connection dialing timeout, in ms (default 5000) -h, –help help for run -i, –interval int Interval, in seconds, between stats updates (default 1) -s, –sleep int Time you want to sleep between connections, in ms (default 10)”>
% tcpgoon --help
tcpgoon tests concurrent connections towards a server listening on a TCP port
Usage: tcpgoon [command]
Available Commands: Help about any run Run tcpgoon version Show tcpgoon version
Flags: -h, --help tcpgoon
Use more information about a command.
% tcpgoon run --help
Run tcpgoon
Usage: tcpgoon run [flags] host port
Flags: -y, --assume-yes Force execution without asking confirmation -c, --connections int Number of connections you want to open (default 100) -d, --debug Print debugging information to the standard error -t, --dial-timeout int Connection dialing timeout, ms (default 5000) -h, --help run -i, --interval int Interval, seconds, between stats updates (default 1) -s, --sleep int Time you want to sleep between connections, ms (default 10)
Examples
Successful execution (connections were opened as expected):
Stressing TCP connections against a server/application facilitates the detection of bottlenecks/issues limiting the capacity of this server/application to accept/keep a specific (and potentially) large number of parallel connections. Some examples of typical (configuration) issues:
OS configuration (TCP backlog, network drivers buffers),
number of file descriptors/processes the server can use,
application listener properties…
These limitations may pass unnoticed in actual application-l7 stress tests, given other bottlenecks can arise earlier than these limitations, or degradation scenarios and/or special conditions may not be reproduced during the stress tests execution, but in real life (lots of connections queued because of a dependency taking longer to reply than it usually does?)
hping is not an actual option for this use case given it won’t complete a 3-way handshake, so the connection will not reach the accept() syscall of your server/application or fill up your TCP backlog.
Where does the project name come from?
Goon: /ɡuːn/ noun informal; noun: goon; plural noun: goons ;
...
2.
NORTH AMERICAN
a bully or thug, especially a member of an armed or security force.
...
Authors
Especial thanks to…
Development information
TO-DO
We do use Github issues to track bugs, improvements and feature requests. Do not hesitate to raise new ones, or solve them for us by raising PRs 😉
Project structure
This project uses a layered topology, where cmd (complemented by cmdutil) takes care of commands/flags/arguments and uses mtcpclient, which owns and knows everything about “multiple TCP connections” (including reporting), while tcpclient only cares about managing single TCP connections. tcpserver is just there as a dependency for the other packages’ tests.
Do not edit README.md directly, as your changes will be lost. Consider README.src.md and the execution (requires godepgraph and Graphviz) of:
% ./_script/readme_generator
Samples injected in the readme can be found in the _script/readme_generator_samples/ directory.
Testing locally
You can use the standard go test command, or use our scripts we also run as CI.
Main tests execution:
Emulation of a travis job execution using docker (of course, it needs docker):
% COVERALLS_TOKEN= ./_script/cibuild-docker
And also emulating a travis job deployment (it publishes new binaries providing successful tests and the right credentials, unless you also use the -r flag / dry-run):
% COVERALLS_TOKEN= ./_script/cibuild-docker -d
Windows 10 позволяет легко подключаться к сети и интернету с помощью проводного или беспроводного соединения. Тем не менее, иногда приходится что-то настраивать вручную или устранять проблемы с подключением, и именно тогда вам могут пригодиться многие встроенные инструменты командной строки.
Способ решения найдется почти на любую проблему. Например, ipconfig и ping — это одни из основных инструментов для просмотра сетевых настроек и устранения неполадок подключения. Если проблема связана с маршрутизацией, команда route сможет отобразить текущую таблицу маршрутизации, а с помощью инструмента nslookup можно диагностировать проблемы DNS.
В этой инструкции мы расскажем о восьми инструментах командной строки, которые помогут устранить сетевые проблемы на устройстве.
IPConfig
Инструмент ipconfig (Internet Protocol configuration) является одним из наиболее распространенных и позволяет запрашивать и показывать текущую конфигурацию сети TCP/IP (Transmission Control Protocol/Internet Protocol). Команда также включает в себя опции для выполнения таких действий, как обновление параметров протокола динамической конфигурации хоста (DHCP) и Системы доменных имен (DNS).
Показать конфигурацию сети
Чтобы начать работу с ipconfig, проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы просмотреть сводку конфигурации сети TCP/IP, и нажмите Enter: ipconfigНа заметку: в командной строке можно использовать команду cls, чтобы очистить экран после того, как информация больше не будет нужна.
Введите следующую команду, чтобы просмотреть всю конфигурацию сети TCP/IP, и нажмите Enter: ipconfig /all
После выполнения этих шагов у вас будет обзор всей конфигурации TCP/IP компьютера.
Обновление сетевых настроек
Чтобы освободить и обновить сетевую конфигурацию с помощью командной строки, проделайте следующее:
Откройте Пуск. Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора. Введите следующую команду, чтобы удалить текущую конфигурацию сети, и нажмите Enter:
Введите следующую команду, чтобы изменить конфигурацию сети, и нажмите Enter:
Обновление настроек DNS
Чтобы сбросить и перестроить текущие записи кэша DNS, проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы очистить системный кэш DNS на устройстве, и нажмите Enter: ipconfig /flushdns
После выполнения этих шагов записи, хранящиеся в кэше DNS Windows 10, будут удалены и обновлены. Обычно эта команда нужна, когда вы не можете подключиться к другому компьютеру или сайту с помощью хоста или доменного имени из-за устаревшей информации в локальном кэше.
Ping
Ping — еще один важный сетевой инструмент. Он позволяет отправлять сообщения эхо-запроса ICMP (Internet Control Message Protocol) для проверки IP-соединения с другими устройствами, будь то другой компьютер в сети или интернет-сервис.
Проверка подключения устройства
Чтобы проверить сетевое подключение с помощью команды ping, проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду для отправки эхо-запросов ICMP для проверки подключения и нажмите Enter: ping IP-OR-DOMAIN В этой команде замените IP-OR-DOMAIN фактическим IP-адресом или доменным именем компьютера или службы, которые хотите протестировать. Например, эта команда проверяет связь между локальным устройством и маршрутизатором: ping 10.0.0.1На заметку: если вы используете опцию -a (например, ping -a 10.0.0.1), то команда также преобразует адрес в имя хоста
(Опционально) Введите следующую команду для проверки сетевого стека локального компьютера и нажмите Enter: ping 127.0.0.1 или ping loopback
После запуска команды получение ответа означает, что сетевой стек в Windows 10 запущен и работает. Это то же самое, что пинговать устройство, используя его собственный сетевой адрес.
После выполнения этих шагов, если вы получите четыре успешных эхо-ответа от пункта назначения, это будет значить, что устройство может общаться с удаленным хостом. Если время ожидания запроса истекло, значит, возникла проблема. Причин может быть много.
Если дело в подключении, пропингуйте локальный компьютер, чтобы убедиться, что сетевой стек работает. Затем проверьте подключение к маршрутизатору, чтобы убедиться, что проблема не в локальной сети. Затем попробуйте пропинговать веб-сайт, чтобы выяснить, есть ли проблема с подключением к интернету или удаленным хостом. Если удаленное устройство или служба блокирует протокол ICMP, отклика на команду не будет.
Как диагностировать потерю пакетов
Команда ping включает в себя ряд параметров, к которым можно получить доступ с помощью команды ping/? , и один из этих параметров — возможность установить время запуска инструмента. Он может пригодиться для проверки потерянных пакетов при устранении неполадок подключения.
Чтобы выполнить команду ping в течение определенного периода времени, выполните следующие действия:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы продолжить пинг до остановки, и нажмите клавишу Enter: ping IP-OR-DOMAIN -t В этой команде замените IP-OR-DOMAIN фактическим IP-адресом или доменным именем компьютера или службы, которые хотите протестировать. Например, эта команда проверяет связь между локальным устройством и маршрутизатором 60 секунд: ping 10.0.0.1 -t
Используйте сочетание клавиш Control + C, чтобы остановить пинг.
После выполнения этих шагов будут выведены успешные и непрошедшие запросы, по которым можно будет понять, как устранить неполадки и проблемы с подключением. В локальной сети администраторы обычно используют команду ping, чтобы узнать о быстром выходе службы из строя. Также этот инструмент позволяет узнать, что сервер снова запущен и работает при удаленном перезапуске сервера.
Tracert
В Windows 10 также есть инструмент tracert (Trace Route) — он позволяет определить сетевой путь к месту назначения с помощью серии эхо-запросов ICMP. Однако, в отличие от команды ping, каждый запрос включает в себя значение TTL (Time to Live) — каждый раз оно увеличивается на единицу, позволяя отображать список пройденных маршрутов и продолжительности запросов.
Чтобы проследить маршрут до пункта назначения с помощью командной строки, выполните следующие действия:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы увидеть путь к месту назначения, и нажмите Enter: tracert IP-OR-DOMAIN В этой команде замените IP-OR-DOMAIN фактическим IP-адресом или доменным именем назначения, неполадки для которого вы хотите устранить. Например, эта команда позволяет просмотреть путь пакетов к Google.com: tracert google.com
(Опционально) Введите следующую команду, чтобы настроить количество шагов к пункту назначения, и нажмите Enter: tracert -h HOP-COUNT IP-OR-DOMAIN В этой команде замените IP-OR-DOMAIN фактическим IP-адресом или доменным именем для назначения, неполадки для которого вы хотите устранить, и HOP-COUNT на количество переходов, которое вы хотите отследить. Например, эта команда устанавливает предел в 5 шагов (узлов) до места назначения: tracert -h 5 google.com
После выполнения этих шагов вы сможете отследить, достижим ли пункт назначения и есть ли проблемы с сетью на этом пути.
Как и инструмент ping, tracert включает в себя несколько параметров, которые можно просмотреть с помощью команды tracert/? .
Nslookup
Инструмент nslookup (Name Server Lookup) может показать важную информацию для устранения неполадок и решения проблем, связанных с DNS. Инструмент включает в себя интерактивный и неинтерактивный режимы. Неинтерактивный режим используется гораздо чаще — он подразумевает полный набор команды, чтобы получить необходимую информацию.
Чтобы начать работу с nslookup, проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы найти локальное DNS-имя и адрес, и нажмите Enter: nslookup На заметку: эта команда также открывает интерактивный режим nslookup.
Подтвердите текущую информацию DNS.
Введите следующую команду для выхода из интерактивного режима и нажмите клавишу Enter: exit
Введите следующую команду, чтобы определить имя и адрес конкретного сервера, и нажмите Enter: nslookup IP-ADDRESS В команде замените IP-ADDRESS на адрес удаленного устройства. Например, эта команда ищет IP-адрес 172.217.165.142: nslookup 172.217.165.142
Введите следующую команду, чтобы определить адрес конкретного сервера, и нажмите Enter: nslookup DOMAIN-NAME В команде замените DOMAIN-NAME на адрес удаленного устройства. Например, эта команда ищет IP-адрес Google.com: nslookup google.com
Netstat
Инструмент netstat (Network Statistics) отображает статистику для всех сетевых подключений. Он позволяет анализировать открытые и подключенные порты, чтобы отслеживать и устранять сетевые проблемы в Windows 10 и приложениях.
При использовании инструмента netstat можно просмотреть активные сетевые подключения и ожидающие соединения порты. Также можно увидеть статистику сетевых адаптеров и протоколов, отобразить текущую таблицу маршрутизации и многое другое.
Чтобы начать работу с netstat, проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы отобразить все активные TCP-соединения, и нажмите Enter: netstat
(Опционально) Введите следующую команду для отображения активных соединений с числовым IP-адресом и номером порта, чтобы не пришлось определять имена, и нажмите Enter: netstat -n
(Опционально) Введите следующую команду, чтобы обновлять информацию с определенным интервалом, и нажмите клавишу Enter: netstat -n INTERVAL В команде обязательно замените INTERVAL на число в секундах, чтобы обозначить необходимый интервал. Например, эта команда обновляет статистику каждые пять секунд: netstat -n 5 На заметку: при использовании параметра interval команду можно завершить с помощью сочетания клавиш Ctrl + C в консоли.
Команда отобразит список всех активных соединений в четырех столбцах.Proto отображает протокол подключения, включая TCP или UDP. Local Address отображает IP-адрес устройства, а через точку с запятой — номер порта подключения; двойная точка с запятой внутри скобок указывает на локальный IPv6-адрес; адрес 0.0.0.0 также относится к локальному адресу. Foreign Address показывает IP-адрес удаленного компьютера (или полное доменное имя) с номером порта после точки с запятой (например, https, http, microsoft-ds, wsd). State показывает, является ли соединение активным (установленным), был ли порт был закрыт (time_wait), или что программа не закрыла порт(close_wait). Другие доступные состояния включают в себя: closed, fin_wait_1, fin_wait_2, last_ack, listen, syn_received, syn_send и timed_wait.
ARP
Windows 10 поддерживает таблицу arp (Address Resolution Protocol), в которой хранятся записи IP to Media Access Control (MAC), разрешенные системой. Инструмент arp позволяет просматривать всю таблицу, изменять записи и использовать ее для определения MAC-адреса удаленного компьютера.
Обычно информация о MAC-адресах не требуется, но бывают ситуации, когда она может пригодиться. Например, при устранении сетевых неполадок на уровне канала передачи данных (коммутация) или при ограничении доступа или фильтрации контента по сети для определенных устройств.
Чтобы начать работу с nslookup проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы просмотреть текущий кэш таблиц arp, и нажмите Enter: arp -a
Введите следующую команду, чтобы определить MAC-адрес удаленного устройства, и нажмите Enter: arp -a IP В команде замените IP на адрес назначения. Например, эта команда показывает физический адрес назначения 10.1.4.113: arp -a 10.1.4.108
Чтобы узнать все доступные параметры, используйте команду arp/? — она перечислит все параметры с их соответствующими описаниями.
Route
Инструмент route отображает таблицу маршрутизации, которая позволяет Windows 10 понимать сеть и взаимодействовать с другими устройствами и службами. Инструмент также предлагает некоторые опции для изменения и очистки таблицы по мере необходимости.
Как и в случае с инструментом arp, таблица маршрутизации обычно не требуется, но может пригодиться для устранении связанных с ней проблем.
Чтобы просмотреть или очистить таблицу маршрутизации, проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора. Введите следующую команду, чтобы просмотреть таблицу маршрутизации, и нажмите Enter: route print
Подтвердите информацию таблицы маршрутизации.
(Опционально) Введите следующую команду, чтобы очистить таблицу маршрутизации, и нажмите Enter: route -f На заметку: при выполнении этой команды устройство потеряет сетевое подключение, так как система перестанет понимать топологию сети. После выполнения команды перезагрузите компьютер, чтобы позволить сетевому стеку перестроить таблицу маршрутизации. Обычно таблицу очищать не нужно, если только вы не изменили записи и хотите ее сбросить.
После выполнения этих шагов вы получите представление о таблице маршрутизации и о том, как очистить информацию.
Команду route /? также можно использовать для просмотра списка доступных параметров, включая параметры изменения сетевых показателей, указания шлюза, добавления нового маршрута и многого другого. Однако, если вы не понимаете, как работает сеть, изменять эти параметры не рекомендуется.
Netsh
netsh (Network Shell) — это классический инструмент командной строки, который позволяет отображать и изменять практически любую сетевую конфигурацию. Например, им можно воспользоваться для просмотра текущей конфигурации сети, управления беспроводными соединениями, сброса сетевого стека для устранения наиболее распространенных проблем, включения или отключения брандмауэра и многого другого.
Чтобы начать работу с инструментом командной строки netsh, проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы просмотреть список доступных команд (контекстов), и нажмите Enter: netsh /?
Введите следующую команду, чтобы просмотреть список доступных подкоманд (субтекстов) для конкретного параметра, и нажмите Enter: netsh CONTEXT-COMMAND В команде измените CONTEXT-COMMAND на команду, включающую дополнительные параметры. Например, эта команда показывает команды, доступные для управления брандмауэром с помощью netsh: netsh advfirewall /?
После выполнения этих шагов вы узнаете, как перемещаться между командами и подкомандами netsh для управления сетевыми настройками.
Сброс системного сетевого стека
Чтобы сбросить сетевой стек для решения наиболее распространенных проблем подключения, выполните следующие действия:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду для выхода из интерактивного режима и нажмите Enter: netsh winsock reset
Перезагрузите компьютер.
После выполнения этих шагов конфигурация winsock будет сброшена, и это, скорее всего, позволит решить проблемы с подключением к сети и интернету.
Экспорт и импорт конфигурации сети
Для экспорта конфигурации сети с помощью netsh проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду для экспорта текущей конфигурации для всех сетевых адаптеров и нажмите Enter: netsh -c interface dump>PATH\TO\EXPORTED.txt В команде замените PATH\TO\EXPORTED.txt на указание пути и имени файла для хранения конфигурации. Например, следующая команда экспортирует настройки в файл netshconfig.txt : netsh -c interface dump>c:\netshconfig.txt
После выполнения этих шагов вы можете открыть файл в любом текстовом редакторе и просмотреть экспортированную конфигурацию.
Импорт конфигурации сети
Для импорта параметров конфигурации сети проделайте следующее:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы импортировать конфигурацию сети, и нажмите Enter: netsh -c interface dump>PATH\TO\IMPORTED.txt В команде замените PATH\TO\EXPORTED.txt на указание пути и имени файла, который вы хотите использовать в качестве конфигурации. Например, следующая команда импортирует настройки из файла netshconfig.txt : netsh -f c:\netshconfig.txt
После выполнения этих шагов новая сетевая конфигурация импортируется и применится к Windows 10.
Включение и отключение брандмауэра
Чтобы включить брандмауэр Windows 10 с помощью netsh, выполните следующие действия:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы активировать брэндмауэр по умолчанию, и нажмите Enter: netsh advfirewall set currentprofile state on
После выполнения этих шагов брандмауэр Защитника Windows включится.
Отключить брандмауэр
Чтобы отключить брандмауэр, выполните следующие действия:
Откройте Пуск.
Найдите Командную строку, щелкните правой кнопкой мыши верхний результат и выберите Запуск от имени администратора.
Введите следующую команду, чтобы отключить брандмауэр по умолчанию, и нажмите Enter: netsh advfirewall set currentprofile state off
После выполнения этих шагов брандмауэр Защитника Windows отключится.
На Windows 10 существует множество инструментов командной строки, PowerShell и графических приложений, которые можно использовать для изменения параметров и устранения неполадок в сети. Тем не менее, в этой инструкции мы сконцентрировались только на том, как начать работу с некоторыми из самых распространенных инструментов именно командной строки.
Display Only IPv4 Ports and Sockets
We can use -p ip option to filter and show only IPv4 connections. This can be useful generally because the IPv6 protocol is not common.
> netstat -p ip
TCP States for netstat Command
As we know TCP protocol provides reliable data transfer between hosts. TCP implements sessions to provide this reliability. From start to end there are different states in a TCP session. Here the sequence and meaning of TCP states.
LISTENING means the port is listening but do not have any connection with a remote host
ESTABLISHED the connection established and communicating with the remote host
TIME_WAIT the connection is in a wait situations
CLOSE_WAIT the connection is the closing phase
CLOSED the connection is closed
SYN_RECEIVED the sync flag received to start the connection
RHEL 6 (nc-1. 84)
Installation:
$ sudo yum install nc
Examples:
$ nc -w 2 -v canyouseeme.org 80 </dev/null; echo $?
Connection to canyouseeme.org 80 port [tcp/http] succeeded!
0
$ nc -w 2 -v canyouseeme.org 81 </dev/null; echo $?
nc: connect to canyouseeme.org port 81 (tcp) timed out: Operation now in progress
1
If the hostname maps to multiple IPs, the above failing command will cycle through many or all of them. For example:
$ nc -w 2 -v microsoft.com 81 </dev/null; echo $?
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
nc: connect to microsoft.com port 81 (tcp) timed out: Operation now in progress
1
We can also filter and show only UDP protocol ports with -p udp option. Here we provided -a to list UDP too.
> netstat -p udp -a
Display Only UDP Protocol
As we can see there is no TCP related port or connection information in this example and all UDP ports are currently listening mode without a connection state. This is because the UDP protocol is a connectionless protocol that does not create a session for data transmission.
Display All TCP and UDP Connections with Listening Ports
TCP is the most used protocol for the transmission of packets between different hosts. In a regular usage for a host, there will be a lot of TCP connections in different phases. We can display all these connections with -a option like below.
> netstat -a
Display All TCP Connections
Proto is the protocol the listening port is running. Generally, TCP and UDP are used.
Local Address is the local or current system IP address and ports number. The IP address and the port number are delimited with the :. 0.0.0.0 means all local IP addresses or network interfaces where 127.0.0.1 means only localhost or current system.
Foreign Address is the remote IP address which is initiated a connection. Like Local address, IP address and the port number are delimited with the :.
State will provide the current status of the given port. A port can be listening which means accepting connections or CLOSED recently closed etc. More details about the port or TCP states can be found below.
Show process ID
netstat -o
command shows all active TCP connections like
netstat
, but with the difference that adds a fifth column to display the Process ID (PID) for each connection. The processes available in this view are the same in the “Details” tab of Task Manager, which also reveals the application using the connection.
Source: Windows Central (Image credit: Source: Windows Central)
Display Fully Qualified Domain Name
Normally netstat will list hostnames in a simple manner and in a fast way. It can skip some domain names too. We can for netstat to print fully qualified domain names with -f option.
> netstat -f
Display Fully Qualified Domain Name
We can see that only resolved DNS names or fully qualified domain names are shown like oracle.com.
Display Information Interactively
If we need to list given options output interactively to monitor the metrics we can use interactive mode. Interactive mode is enabled by providing interval value to print output. This feature does not needs any option we will only provide interval value which is 2 in this case.
> netstat -s -p tcp 2
Display Only TCP Protocol Statistics
We can only list TCP protocol-related statistics with -s -p tcp option.
> netstat -s -p tcp
Display Only TCP Protocol Statistics
Active Opens will list currently opened connection count. In this example, this is 104.
aPassive Opens will list open connections but not transferred any data recently. In this example, this is 15.
Failed Connection Attempts will list connection tries or attempts not completed so there are no started connections which are 4.
Reset Connections will list connections that ended with the RST TCP flag.
Current Connections will list currently opened connection count which is 5 in this example.
Segments Received will list the count of received TCP segments.
Segments Sent will list the count of sent TCP segments.
Segments Retransmitted will list the count of retransmitted TCP segments.
Show executable information
netstat -b
command lists all the executables (applications) associated with each connection. Sometimes, applications may open multiple connections.
Source: Windows Central (Image credit: Source: Windows Central)
Show statistics by Protocol
netstat -s
shows network statistics for all available protocols, including TCP, UDP, ICMP, and IP protocols (version 4 and 6).
Source: Windows Central (Image credit: Source: Windows Central)
Show offload state connections
netstat -t
command generates a list of the current connection offload state. The offload state refers to the TCP Chimney Offload (opens in new tab), which is a feature that transfers the network workload from the processor to the network adapter during data transmissions. The “InHost” value indicates that offloading isn’t enabled, and the “Offload” means that the feature is transferring the workload to the network adapter. (This feature is only present on supported network adapters.)
Display Only ICMP Protocol Statistics
We can list only ICMP related statistics with -s -p icmp option.
Echo Replies: ICMP Echo replies which are generally used for ping or ping command.
Show connections by Protocol
netstat -p
can be used to display connections per-protocol that you have to specify using
tcp
udp
tcpv6
udpv6
next to the command. For example, you can use the
netstat -p tcp
to view a list of TCP connections.
Source: Windows Central (Image credit: Source: Windows Central)
Display Routing Table
Routing is used to set IP packets first-hop according to their destination. Our system route information can be listed with -r option.
> netstat -r
Display Routing Table
As we can see the default route is printed in the first line which IP address is 192.168.122.1 .
Show FQDNS for foreign addresses
netstat -f
Source: Windows Central (Image credit: Source: Windows Central)
Using nc
Note that a backward incompatible version of nc gets installed on RHEL 7.
Combine parameters
When using the
netstat
command, you can also combine the parameters to display various information together for many cases.
For example, the
-e
parameter can also be used with the
-s
parameter to see statistics for each available protocol, and the
-o
parameter can be combined with
-a
-n
-p
Source: Windows Central (Image credit: Source: Windows Central)
netstat -p
command, you append the
s
parameter, you can display statistics from even more protocols, including
icmp
ip
icmpv6
ipv6
Also, when using more than one parameter, you can combine them with a single
-
. For example, instead of writing the command
netstat -e -s
, you can write it like this:
netstat -es
Source: Windows Central (Image credit: Source: Windows Central)
If you want to see all the available parameters and additional help, you can always use the
netstat /?
TOC
Using bash and timeout
Command
Examples
Using nc
Command
RHEL 6 (nc-1.84)
Installation
Examples
RHEL 7 (nmap-ncat-6.40)
Installation
Examples
Remarks
Синтаксис и параметры команды NETSTAT
-a – вывод всех активных подключений TCP и прослушиваемых компьютером портов TCP и UDP.
-e – вывод статистики Ethernet, например количества отправленных и принятых байтов и пакетов. Этот параметр может комбинироваться с ключом -s.
-n – вывод активных подключений TCP с отображением адресов и номеров портов в числовом формате без попыток определения имен.
-o – вывод активных подключений TCP и включение кода процесса (PID) для каждого подключения. Код процесса позволяет найти приложение на вкладке Процессы диспетчера задач Windows. Этот параметр может комбинироваться с ключами -a, -n и -p.
-p протокол – вывод подключений для протокола, указанного параметром протокол. В этом случае параметр протокол может принимать значения tcp, udp, tcpv6 или udpv6. Если данный параметр используется с ключом -s для вывода статистики по протоколу, параметр протокол может иметь значение tcp, udp, icmp, ip, tcpv6, udpv6, icmpv6 или ipv6.
-s – вывод статистики по протоколу. По умолчанию выводится статистика для протоколов TCP, UDP, ICMP и IP. Если установлен протокол IPv6 для Windows XP, отображается статистика для протоколов TCP через IPv6, UDP через IPv6, ICMPv6 и IPv6. Параметр -p может использоваться для указания набора протоколов.
-r – вывод содержимого таблицы маршрутизации IP. Эта команда эквивалентна команде route print.
интервал – обновление выбранных данных с интервалом, определенным параметром интервал (в секундах). Нажатие клавиш CTRL+C останавливает обновление. Если этот параметр пропущен, netstat выводит выбранные данные только один раз.
/? – отображение справки в командной строке.
Примеры команды NETSTAT
Пример работы команды Netstat на Windows 10 показан на рисунке выше, утилита работает на всех версиях операционных систем Windows.
Для отображения справки по команде введите в командной строке netstat /?;
Для вывода статистики Ethernet и статистики по всем протоколам введите следующую команду: netstat -e -s;
Для вывода статистики только по протоколам TCP и UDP введите следующую команду: netstat -s -p tcp udp;
Для вывода активных подключений TCP и кодов процессов каждые 5 секунд введите следующую команду: netstat -o 5.
command generates a statistic of the network interface, which shows information like the number of bytes, unicast and non-unicast sent and received packets. You can also see discarded packets and errors and unknown protocols, which can you troubleshoot networking problems.
Source: Windows Central (Image credit: Source: Windows Central)
Display Only IPv6 Ports and Sockets
We can use -p ipv6 option to filter and show only IPv6 connections about the netstat command.
> netstat -p ipv6
Show NetworkDirect connections
netstat -x
NetworkDirect (opens in new tab) is a specification for Remote Direct Memory Access (RDMA), which is a process that allows fast data transfers using the network adapter, freeing up the processor to perform other tasks. Usually, you’ll never use this command unless you’re using the server version of Windows or a high-performance application with a network adapter that supports this feature.
Display Ethernet Statistics
Ethernet or MAC generally used for the same meaning. Ethernet is a Layer 2 protocol used to communicate in our LAN with other hosts and mostly with a gateway that is used to access other networks or the internet. We can list detailed information about the ethernet protocol. We will use -e option to list ethernet statistics.
> netstat -e
Display Ethernet Statistics
Received column is used to specify the received sizes.
Sent column is used to specify the sent sizes.
Bytes is used successfully completed transfers.
Unicast packets generally related to the UDP protocol where there is no connection and session management.
Non-unicast
Discards is the packets that are discarded because of the problems.
Errors show the sizes of the packets where errors occurred.
Unknown protocols show the protocols currently unknown by the TCP/IP stack.
Информация TCP/IP
Ранние версии Netstat не могли выводить имя процесса, ответственного за данное соединение. Netstat имеет более развитые функциональные возможности, чем просто мониторинг конечных точек (endpoint), и с учетом различных параметров, она может предоставлять сетевую статистику отсортированную или отфильтрованную по протоколу, или выводить таблицу маршрутизации. Так как Netstat является приложением командной строки, то ее выходные данные могут быть по конвейер) переданы другим приложениям или записаны в файл.
Netstat может выводить последовательность компонент, — исполняемые модули, динамические библиотеки (DLL) и т.д., — задействованных в установлении и прослушивании! единения. TCPView имеет ограничение: может выводить сведения только о’ конечных точках, которые были инициированы после загрузки TCPView.
С TCPView гораздо проще работать, чем с Netstat. Можно периодически получать копию состояния сетевых соединений. TCPView позволяет завершать соединения в реальном времени, чего Netstat делать не может.
TCPView выводит имя процесса, ID процесса (PID), локальный адрес и порт, удаленный адрес и порт, а также статус соединения.
Show routing table
netstat -r
command displays the current network routing table that lists all the routes to destinations and matrics known by the device, for IP version 4 and version 6 (if applicable). If the returned information looks familiar, it’s because you can also output the data using the
route print
Source: Windows Central (Image credit: Source: Windows Central)
RHEL 7 (nmap-ncat-6. 40)
Installation:
$ sudo yum install nmap-ncat
Examples:
$ nc -w 2 -v canyouseeme.org 80 </dev/null; echo $?
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Connected to 52.202.215.126:80.
Ncat: 0 bytes sent, 0 bytes received in 0.22 seconds.
0
If the hostname maps to multiple IPs, the above failing command will cycle through many or all of them. For example:
$ nc -w 2 -v microsoft.com 81 </dev/null; echo $?
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Connection to 104.43.195.251 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 23.100.122.175 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 23.96.52.53 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection to 191.239.213.197 failed: Connection timed out.
Ncat: Trying next address...
Ncat: Connection timed out.
1
Using bash and timeout
Note that timeout should be present with RHEL 6+, or is alternatively found in GNU coreutils 8.22. On MacOS, install it using brew install coreutils and use it as gtimeout.
How to search netstat details on Windows 10
In addition to displaying all the available statistic information, you can also output only the certain details you need using these steps:
Open Start.
Search for Command Prompt, right-click the top result, and select the Run as administrator option.
Type the following command to list all the connections that have the state set to LISTENING and press Enter:netstat -q | findstr STRINGIn the command, make sure to replace STRING for the information you want to list. Also, the findstr option is case sensitive, which means that you must enter the string you want to find with the exact casing.This example lists all the connections that have the state set to “LISTENING.”netstat -q | findstr LISTENINGThis other example shows all the connections from a foreign server FQDN, in this case, Amazon:netstat -f | findstr amazonAs you can see, you only need to type part of the string to return a result.
Source: Windows Central (Image credit: Source: Windows Central)
The findstr command isn’t part of the netstat tool. It’s a simple command to search for a text string in a file, but you can use it with many of the netstat commands to make more sense of the information you’re viewing.
The netstat command is available on Windows 10, but you can also find it on Windows Server, Windows 8.x, Windows 7, and older versions. The tool is not exclusive to Windows either, as it’s also available across platforms, including Linux and macOS. Even though the parameters and syntax may be different, they all are very similar.
All the latest news, reviews, and guides for Windows and Xbox diehards.
Command
Note that the command below is unique in that it is identical for both RHEL 6 and 7. It’s just the installation and output that are different.
commands can produce a list of all the connections with the listening and bound non-listening ports.
Source: Windows Central (Image credit: Source: Windows Central)
Remarks
The -v (--verbose) argument and the echo $? command are of course for illustration only.
Netstat Command Syntax
netstat OPTIONS
OPTIONS will set different options and arguments about the netstat command behavior.
Display Numeric Presentation of Ports and Hostname
Host and ports generally have numeric and text presentations. netstat command by default try to resolve the hostname and port name into text format. If we need to get the host and port numeric information like IP address and the port number we can use -n option.
> netstat -n
Display Numeric Presentation of Ports and Hostname
Show numerical form
netstat -n
command displays the addresses and ports in numerical form. For example, 54.230.157.50:443.
Source: Windows Central (Image credit: Source: Windows Central)
netstat command provides extensive filtering options according to protocols. We can provide a filter option with -p and protocol name. In this example, we will filter and show only TCP protocol.
> netstat -p tcp
Display Only TCP Protocol
As we can see there is no UDP protocol related port and connection information.
How to use netstat on Windows 10
To get started with netstat, use these steps:
Open Start.
Search for Command Prompt, right-click the top result, and select the Run as administrator option.
Type the following command to show all active TCP connections and press Enter:netstat
Source: Windows Central (Image credit: Source: Windows Central)
(Optional) Type the following command to display active connections showing numeric IP address and port number instead of trying to determine the names and press Enter:netstat -n
Source: Windows Central (Image credit: Source: Windows Central)
(Optional) Type the following command to refresh the information at a specific interval and press Enter:netstat -n INTERVALIn the command, make sure to replace INTERVAL for the number (in seconds) you want to redisplay the information.This example refreshes the command in question every five seconds:netstat -n 5Quick note: When using the interval parameter, you can terminate the command using the Ctrl + C keyboard shortcut in the console.
Source: Windows Central (Image credit: Source: Windows Central)
Once you execute the command, it’ll return a list of all active connections in four columns, including:
Proto: Shows the connection protocol (TCP or UDP).
Local Address: Shows the computer’s IP address followed by a semicolon with a port number of the connection. The double-semicolon inside brackets indicates the local IPv6 address, and “0.0.0.0” refers to the local address too.
Foreign Address: Lists the remote device’s IP (or FQDN) address with the port number after semicolon port name (for example, https, http, microsoft-ds, wsd).
State: Indicates where the connection is active (established), the local port has been closed (time_wait), and the program hasn’t closed the port (close_wait). Other status include, closed, fin_wait_1, fin_wait_2, last_ack, listen, syn_received, syn_send, and timed_wait.
Show connection template
netstat -y
command displays TCP connections templates for all connections.
Source: Windows Central (Image credit: Source: Windows Central)
Display IPv4 ve IPv6 Statistics
netstat command provides a lot of statistical information about the network stack. These statistics provide detailed metrics about protocols. We can list this statistical information with -s option.
> netstat -s
Display Statistics
Packets Received: The total IP packets received.
Received Header Errors: The total number of headers errors of the received packets.
Received Address Errors: The total number of address errors of the received packets.
Unknown Protocols Received: The total number of protocols which is unknown.
Received Packets Discarded: The total number of packets that are discarded after received.
Show active and inactive connections
netstat -a
command displays all active and inactive connections, and the TCP and UDP ports the device is currently listening.
Source: Windows Central (Image credit: Source: Windows Central)
Display Connection or Ports Process Name
> netstat -b
Display Connection or Ports Process Name
We can see from the output that chrome.exe. established a connection with a remote host over https protocol.
How to use netstat parameters on Windows 10
The tool also includes several parameters that you can use in Command Prompt to display different information about the network connections.
Display Connection or Ports Process ID
All ports and connections are opened and managed by processes in the operating system. For example, Apache is a web server and uses TCP 80 for listening to HTTP requests. We can list processes id of given connection or port with -o option.
> netstat -o
Display Connection or Ports Process ID
We can see that also PID or Process ID is provided which is the current application process ID which listens given port and interface.