Route Add Windows Command to Add Persistent Static Route in Windows 10

What exactly is the routing table in Windows and Linux, why is it useful and how can we make sense of it?

I’ll answer all these questions today by showing you how to display the routing table on your computer and then showing you what it all means.

You’ll also get a little primer on how basic network communication works.  Also, if the differences between IP addresses and MAC addresses ever confused you then you need to read this.

First I just want to mention that routers aren’t the only devices with routing tables.  Almost every network connected device that relies on TCP/IP has a routing table because every device needs to know where to send packets.

Here’s how to view the routing table on your Windows or Linux box.

In Linux, you can conjur the routing table with this command:

netstat -rn

View routing table in Linux

route print

There’s a lot of messy data on the screen but if you pause for a moment you’ll see that it’s actually very organized and coherent.

Route Print Windows 8.1 Routing Table

There are five column of interest here:

  • Network Destination
  • Netmask
  • Gateway
  • Interface
  • Metric

I’m going to break it down but I want to do something different here.  Instead of giving you pedantic definition of each column I want you to really grasp what’s going on.

Пишите нам!
Архитектурная мастерская.
Продвижение сайтов от optimism.ru

Page generation time: 0.0764s (PHP: 64% – SQL: 36%) – SQL queries: 31 – GZIP disabled – Debug off

add static route windows

Adding a static route in Microsoft Windows 10 or Server is done by using the route add command.

route add -p <destination> mask <subnet-mask> <gateway>
route add -p 192.168.1.0 mask 255.255.255.0 10.0.0.1

When you want to add a static route to a single host, use the netmask 255.255.255.255.

route add -p 192.168.1.100 mask 255.255.255.255 10.0.0.1

The most important part of the route add command is the -p option. Without the -p switch, our new route would not be persistent. It will disappear the next time you reboot your Windows PC/Server.

We can print the windows routing table using the route print command. Under the Persistent Routes header, you will see the list of permanent static routes.

Windows routing table
Routing Table
route add -p 192.168.1.0 mask 255.255.255.0 10.0.0.1 metric 5

In case if you have more than one network interface, you could also specify the interface ID using the if command option.

route add -p 192.168.1.0 mask 255.255.255.0 10.0.0.1 if 1

When specifying the network interface, you have to provide the interface ID which you can find using the route print command.

Route Add Windows Command to Add Persistent Static Route in Windows

Did you know that your router isn’t the only device with a routing table?

Yup, any device that relies on TCP/IP for network communications has a routing table – including Windows.

Go ahead and open a command prompt (Windows Key + x + c) and type:

route print

Using route print in Windows

The output is divided into three sections:

  • Interfaces List
  • IPv4 Route Table
  • IPv6 Route Table

The Interfaces List enumerates all your interfaces by MAC address and the next two sections list your dynamic and persistent routes for IPv4 and IPv6.

Each line under Active Routes is a TCP/IP route to a network or a specific device on the network.

To add a route we use the route ADD command to tell Windows which Network to add and then we enter the Subnet mask and Gateway.

So let’s say we’re on the 10.255.70.0 network and the default gateway is 10.255.70.1 and we want to add static route to our management VLAN located on the 172.10.3.0 network.

Assuming our subnet mask is 255.255.248.0 we could add the route like this:

route ADD 172.10.3.0 MASK 255.255.248.0 10.255.70.1

route ADD this network with this mask via this gateway IP.

The only drawback to this method is that after you reboot your static route will go poof!

In order to make it stay we need to make it persistent with the -p modifier.  So just add a -p to the end of the route and it’ll be permenent.

route ADD 172.10.3.0 MASK 255.255.248.0 10.255.70.1 -p
route DELETE 172.10.3.0

That’s it for now!

Как очистить таблицу маршрутизации

При диагностике интернет-соединения для устранения причины неполадок в сети пользователь должен совершить операции по восстановлению доступа, которые связаны с настройками подключения. При невозможности заново поднять сеть можно прибегнуть к процедуре очистки таблицы маршрутизации.

Как очистить таблицу маршрутизации

Очистка таблицы маршрутизации выполняется при невозможности восстановления сетевого подключения другими методами. Для сброса вам потребуется вызвать командную строку и ввести соответствующую команду.

Откройте меню «Пуск» и введите в строке поиска запрос «Командная строка». Левой клавишей мыши кликните на полученном результате и дождитесь появления черно-белого окна, в котором будет необходимо ввести нужный запрос.

Установите курсор в начальное положение и при помощи клавиатуры пропишите команду:

Нажмите Enter, чтобы начать выполнение команды. Подождите несколько секунд до сброса данных и появления новой строчки в окне командной строки. Обнуление таблицы маршрутизации завершено, и вы можете закрыть терминал.

После выполнения процедуры все маршруты, которые указаны в настройках сетевого подключения, будут сброшены. Обнулятся все внесенные пользователями данные, и вы сможете заново вписать настройки вашей сети. Также пропадет доступ к интернету.

Если для осуществления подключения к сети ваш провайдер использует автоматические маршруты и протокол DHCP, таблица маршрутизации будет восстановлена после перезагрузки. Для восстановления настроек не проводите никакие изменения в параметрах адаптера, а перезапустите компьютер, чтобы все ранее внесенные настройки были снова установлены.

В том случае, если после перезагрузки данные не были восстановлены, вам придется вручную прописать необходимые параметры в соответствии с инструкциями вашего провайдера.

Если соединение по-прежнему не работает после перезагрузки компьютера, вы можете обратиться в службу технической поддержки провайдера. Опишите проблему и код ошибки, которая появляется в процессе подключения, а также сообщите операции, которые вы производили для исправления проблемы. Отсутствие доступа к сети может быть связано с оборудованием, установленным на стороне вашего поставщика услуг для выхода в интернет.

Видео по теме

https://youtube.com/watch?v=qP_hiya1wDI%3Fwmode%3Dtransparent

Забыли пароль?
Еще не зарегистрированы?

If you want to see the routing tables, you will have to open a Command Prompt window and then enter the ROUTE PRINT command. Upon doing so, you will see a screen similar to the one that’s shown in Figure A.

image0021133964045000.jpg

Figure A: This is what the Windows routing tables look like

Before I delve into the routing tables, I recommend entering another command into the Command Prompt window. The command is:

The reason I am recommending that you use the IPCONFIG /ALL command is because it shows you how TCP/IP is really set up on the machine. Sure, you could look in the TCP/IP section of the network adapter’s properties sheet, but the information is more reliable if you get it from IPCONFIG. I have seen a couple of instances over the years in which IPCONFIG reported completely different information than what was entered into the machine’s TCP/IP configuration screen. This doesn’t happen often, but if the right type of error occurs, you can experience this type of mismatch. To put it bluntly, the information that’s keyed into the TCP/IP properties sheet reflects how you would like Windows to set up the TCP/IP protocol for the chosen network. The information presented by IPCONFIG shows how Windows has actually configured the protocol.

Even if you haven’t had some bizarre Windows error, it’s still useful to get your configuration information through IPCONFIG. If a machine has multiple network cards, it can be tough to remember which configuration is bound to which card. IPCONFIG lists the various configurations in an easy to read, per NIC basis, as shown in Figure B.

image0041133964045000.jpg

Figure B: The IPCONFIG /ALL displays the machine’s TCP/IP configuration on a per NIC basis

Examining the routing tables

You might be wondering why I had you do an IPCONFIG /ALL when this article is supposed to be discussing routing tables. The reason is that normally you never even look at the routing tables unless you are having problems with your machine. If you are having problems, then the best place to start the troubleshooting process is to compare the information provided by IPCONFIG to the information stored in the routing tables.

As you saw in Figure B, the IPCONFIG /ALL screen displayed some basic TCP/IP information such as the IP address, the default gateway, etc. The routing tables aren’t quite as intuitive though. Therefore, I want to take some time to discuss how to read the routing tables and what the information in the tables means.

In order to understand what the information in these columns mean, you need to understand a little bit about how a router works. A router’s job is to facilitate moving traffic from one network to another. As such, a router will contain multiple network interface cards, each connected to a different network segment.

:/>  Как открыть порт вин 7 и как настроить его

If you look at the Route Print screen, you will notice that the routing tables are divided into five different columns. The first column is the network destination column. This column lists all of the network segments that the router is attached to. The Netmask column provides the subnet mask not of the network interface that’s attached to the segment, but of the segment itself. This basically allows the router to determine the address class for the destination network.

The third column is the gateway column. Once the router has determined which destination network it needs to send the packet to, it looks at the gateway listing. The gateway listing tells the router which IP address the packet should be forwarded through in order to reach the destination network.

The Interface column tells the router which NIC is connected to the appropriate destination network. Technically, the interface column only tells the router the IP address that has been assigned to the NIC that connects the router to the destination network. However, the router is smart enough to know which physical interface the address has been bound to.

The final column in the routing table is the Metric column. Metrics are a science in themselves, but I will try to give you a brief explanation of what they do. The best way that I have ever heard metrics explained is in terms of an airport. Imagine for a moment that I needed to fly from Charlotte, N.C. (the closest major airport to my home in South Carolina) to Miami. Being that the Charlotte airport is pretty big, I have a lot of choices of how I could get to Miami Beach. I could hop a Northwest Airlines flight. It would take me to Detroit and then down to Miami (Detroit is a bit out of the way). Likewise, I could hop a Continental Airlines flight that would take me to Houston, and then to Miami. Another option would be to just take a US Airways flight nonstop to Miami. So which airline should I take?

In real life, there are a lot of factors to consider such as the price of the ticket and the departure times, but let’s assume that everything was equal. If there were no differences between the airlines other than the route, then I would fly the airline that makes the fewest stops. It would get me to my destination more quickly, and since there are fewer stops, there would be less chance of having a problem with my connection, lost luggage, and things like that.

Routing works the same way. Many times, there is more than one way that a router could send a packet. In such a case, it makes sense to send the packet along the shortest (or most reliable) path. This is where the metrics come into play. Windows does not even look at metrics unless there are multiple paths to a destination. If there are multiple paths though, Windows checks the metrics to determine the shortest route. This is an over simplified explanation, but it gets the point across.

Additional routing options

The –f switch is optional. This switch tells Windows to clear the routing table of all gateway entries. If the –f switch is used in conjunction with other commands then all gateway entries will be cleared prior to executing other instructions within the command.

The –p switch makes a specified route persistent. Normally, when a server is rebooted then any routes that you specify via the ROUTE command are removed. The –p switch tells Windows to keep the route even if the system is rebooted.

The command portion of the ROUTE command’s syntax is relatively simple. The command set consists of four options PRINT, ADD, DELETE, and CHANGE. I’ve already shown you the ROUTE PRINT command, but even the ROUTE PRINT command has other options. For example, you can use wild cards with this command. For instance, if you only wanted to print routes pertaining to the 192.x.x.x subnet, you could use the command ROUTE PRINT 192*.

ROUTE ADD 147.0.0.0 255.0.0.0 148.100.100.100

In this command, 147.0.0.0 is the new destination that you are adding. 255.0.0.0 would be the subnet mask for the destination, and 148.100.100.100 would be the gateway address. You can extend the command with the METRIC and IF parameters. Doing so would look something like this:

ROUTE ADD 147.0.0.0 255.0.0.0 148.100.100.100 METRIC 1 IF 1

The metric parameter is optional, but it specifies the metric or number of hops for the route. The IF parameter tells Windows which NIC to use. In this particular case, Windows would use the NIC that’s bound to Windows as interface 1. If you don’t use the IF parameter then Windows will automatically search for the best interface to use.

In this article, I have explained how to use the ROUTE command to display the Windows routing tables and make changes to those tables if necessary. If you need a little extra help, you can get more syntax examples by entering the ROUTE /? Command.

Brien Posey is an award-winning author who has written more than 3,000 articles and written or contributed to 27 books. You can visit Brien’s personal Web site at www.brienposey.com.

Используем Microsoft Easy Fix

Route Add Windows Command to Add Persistent Static Route in Windows 10

В появившемся окне нажимаем на кнопку «Далее» и видим сообщение о том, что необходимо перезагрузить компьютер:

Route Add Windows Command to Add Persistent Static Route in Windows 10

Снова нажимаем на кнопку «Далее». Теперь ждём пока утилита выполнит сброс сети Виндовс и настроек протокола TCP/IP, после чего вернёт нам управление компьютером. Вот и всё! Profit!

PATHPING

Эта команда подобна предыдущей, но может показать намного больше информации. Она так же проверяет маршрут передачи пакетов и определяет, на каких «станциях» данные были утеряны. Исполняться она будет немного дольше, но без этого не обойтись в настройке сетевого подключения Windows 10.

Тут уже мы будем вводить в командную строку:

Параметры командной строки:

  • -g Свободно выбрать маршрут по списку узлов.
  • -h какое максимальное число прыжков при поиске узла.
  • -i нужно использовать указанный адрес источника.
  • -n не надо определять имена узлов по адресам.
  • -p Пауза между отправками пакетов (в мсек).
  • -q Число запросов при каждом прыжке.
  • -w Время ожидания каждого ответа (мсек).
  • -4 Обязательное использование протокола IPv4.
  • -6 Обязательное использование протокола IPv6.
  1. pathping /? – отобразить подсказку по использованию.
  2. pathping google.ru – выполнить трассировку маршрута к узлу google.ru (вы можете добавить свой сайт или IP-адрес).

В результате мы получаем вот такой результат:

Route Add Windows Command to Add Persistent Static Route in Windows 10

TRACERT

TRACERT (Trace Route) работает «в паре» с PING. Вот только с его помощью можно выяснить не скорость передачи данных, а их маршрут. По этой команде высылаются три пакета данных и в результате пользователю отобразиться, через какие маршрутизаторы они проходят.

Чтобы сделать трассировку необходимо использовать команду Windows tracert .

Route Add Windows Command to Add Persistent Static Route in Windows 10

GETMAC

MAC-адрес (Media Access Control) есть на каждом устройстве, которое совместимое с IEEE 802. По её исполнению можно увидеть несколько MAC-адресов, если на компьютере установлено два и больше сетевых адаптеров. Команда показывает такой адрес каждой единицы оборудования.

Можно вводить такие команды:

  • GETMAC /FO csv – тогда получите данные об аппаратных адресах всех сетевых адаптеров на ПК в формате CSV.
  • GETMAC /S SERVER /FO LIST /V – данные о MAC-адресах удаленного ПК с именем SERVER в виде списка. При подключении к удаленному компьютеру используется учетная запись текущего пользователя.
  • GETMAC /S SERVER /U domain\user /P password /FO list /V – результат будет похож на тот, который можно получить при вводе предыдущей команды, однако, при доступе к удаленному ПК нужно использовать указанные имя и пароль.
  • GETMAC /S 192.168.1.1 /U domain\user /P password /FO table /NH – то же, что и в предыдущем примере, но вместо имени удаленного компьютера используется его IP-адрес, и выводятся данные в виде таблицы без полей заголовка.
  • GETMAC /FO LIST /V > C:\mymac.txt – появятся список всех данных о MAC-адресе сетевых адаптеров данного ПК с записью результатов в текстовый файл C:\mymac.txt

Route Add Windows Command to Add Persistent Static Route in Windows 10

Talk to me

In order for a computer to communicate with another computer (or network device) a few things have to happen.

First, the host, which is another name for your computer, tries to figure out if the destination device (a web server, printer, file server etc..>) is on the same network as the host.

If it’s on the same network it just shoots the frame directly to the destination device; however, if it’s off network it sends out a broadcast message saying

Hey, everyone, what’s the MAC address of the default gateway!?

Everyone on the local network gets the message but only the default gateway replies with its MAC address.  Your host adds it as an entry inside its local record known as the ARP cache.  This is so the next time it needs to get off the network it doesn’t have to bother everyone by yelling for that MAC address.

:/>  Дисейбл перевод на русский с английского. Перевод "to disable"

So now your packet has found a way off the island out into the inhospitable waters of the interwebs but how does it actually make its way through the internet?

The network packet is like a little boat floating on a MAC address raft.

Every device on the web has both a MAC and IP address.  As the packet traverses the internet the IP address is static, it doesn’t change; however, each router replaces the source and destination MAC addresses with new ones.

In other words, the MAC address is like a little boat that transports the packet between router islands.  When the packet arrives at the shoreline of one router, the router removes the boat and gives it a new one with it’s MAC address as the source and the next nearest router as the destination MAC.

During packet transmission, both the source and destination IP address never change but the packet is constantly having its old source and destination MAC addresses stripped and added as it moves it’s way from router to router.  The MAC is just a temporary means of getting the packet to the next immediate point but the IP address is the big picture: it tells us how to get to the final destination.

Сброс настроек TCP/IP и DNS в Windows 10

Route Add Windows Command to Add Persistent Static Route in Windows 10

В некоторых случаях для восстановления работы сети на компьютере нужно сделать сброс сетевых настроек. Я так же обычно советую это делать в тех ситуациях, когда у пользователя проблемы только на одном компьютере. Все остальные устройства, использующие эту же сеть, работают нормально. Что нам это даст? Во-первых, это поможет исправить «косяки», которые мог наделать неграмотный юзер в сетевых параметрах. Во-вторых, устранит следы работы вредоносных программ, которые так же могли хозяйничать в системе. Да и сама по себе ОС Windows может заглючить через несколько лет использования без соответствующего обслуживания.

В этой статье я подробно покажу несколько способов как правильно сбросить параметры протокола TCP/IP и DNS — через настройки Windows 10, с помощью командной строки и используя специальную сервисную утилиту от разработчиков (Microsoft Easy Fix). Сброс сети с помощью консоли и дополнительной утилиты можно сделать не только в «десятке», но так же и уже устаревших версиях операционной системы — Windows 8, Windows 7 и даже в серверных версиях!

Bombastic binary

Now we know how the packet traverses the web; however, did your computer know that the packet was destined off the local network?

It’s all about the Netmask (Subnet Mask) and Interface columns.

Look back at the ROUTE PRINT output.

Route Print Windows 8.1 Routing Table

The IP address under Interface is your local IP address.  It’s the IP address of your network adapter.

But an IP address is never naked. It’s always clothed with a Subnet Mask because without the mask the computer has no way of knowing which network the computer actually lives in.

So the computer compares the binary representations of both the Interface and corresponding Netmask to determine the destination Network.

Notice how some values under Gateway say On-link.

That’s because those destination networks are on the same subnet as my host:  In other words, they don’t need to go through a router because their on the same same link as my computer.

Let me show you how the PC knows if a destination network is on its link.

Как удалить статические маршруты. Как добавить маршрут в Windows 10, 8, 7

Маршруты — это сетевые установки, которые используются операционной системой для организации трифака и доступа к локальной сети и в Интернет. С помощью этой странички вы научитесь просматривать, удалять и добавлять маршруты на компьютере с ОС Windows от XP до 10. Все эти действия выполняются в командной строке или ее улучшенном и расширенном аналоге PowerShell.

Хочется также сказать о том, что если вы не уверены в своих знаниях, лучше не изменять данные настройки. Т.к. при неправильном использовании маршрутизации вы можете оставить ваш компьюетр без доступа к сети Интернет.

Просмотр маршрутов

Route Add Windows Command to Add Persistent Static Route in Windows 10

Удаление всех статических маршрутов:

Route Add Windows Command to Add Persistent Static Route in Windows 10

Добавление статического маршрута:

Route Add Windows Command to Add Persistent Static Route in Windows 10

После того, как все маршруты стёрты, естественно пропадёт Интернет. Для того, чтобы он появился вновь, необходимо задать маршрут по умолчанию. Добавляем постоянный маршрут к шлюзу:

В Windows XP/2003 Server после этого появится Интернет. Но если у вас Windows 7/8.1/или 2008/2012 Server, необходимо также выполнить команды:

Ones and Zeros Oh yeah!

If we convert the local host IP address, 10.255.77.167, to binary we get:

  • 00001010
  • 11111111
  • 01001101
  • 10100111

The number 10 is 000000 in binary because both  in that binary number represent 8 and 2 respectively and sum to 10.

8 + 2 = 10.

In the same way, the number 255 is all 1’s in binary: 11111111.

Moving across the binary number 1111111 from right to left the first number, the one furthest to the right, represents 2 to the zeroth power which is 1.

The second number is 2 to the 1st power which is 2.

The third number is 2 to the second power with is 4.

The fourth number is 2 to the 3rd power which is 8.

And this keeps going.

So by the time you get to the last number (remember moving from right-to-left) it’s 2 to the 7th power which is 128.

So in the IP address, 10.255.77.167, we get 255 by adding up all those powers of 2.

We have eight 1’s so we have eight powers of two.

So 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255.

This is how binary works.

Let’s do the number 72 real fast which is 01001000 in binary.

Starting from right side moving toward the left we can skip those three zeros. We’ll stop when we hit the.

So the first 1 in 0100000 is in the 2 to the third power place which is 8.

The other 1 is in the 2 to the 6th place which is 64.

64 + 8 is 72.

Okay, enough of the math, I just wanted to show you how computers think of IP addresses because they don’t see decimal numbers like we do.  On the contrary, computers think, breath and live the monotonous life zeros and ones.

Finding the right network

Your computer determines if the destination is on the right network by comparing the binary representation of the destination address with the netmask.

We already know the IP address 10.255.77.167 is actually:

00001010 11111111 01001101 10100111

And according to the ROUTE PRINT command the Netmask is showing up as 255.255.248.0.

Here’s what that looks like in binary:

11111111 11111111 11111000 00000000

All the 1’s in the netmask reveals which bits belong to the network portion of the IP address and the zeros show the host portion.  The Netmask divides the IP address into two parts: network and host.

If we stack both bits on top of each other we can figure out which network 10.255.77.167 belongs to:

00001010 11111111 01001101 10100111 (10.255.77.167)
11111111 11111111 11111000 00000000 (255.255.248.0)

Starting from the left side and moving right we can do a binary AND operation across each bit to produce the subnetwork.

  • 1 AND 1 = 1
  • 1 AND 0 = 0.

Looking at the first group of 8 bits:

00001010 
11111111

00001010 which is 10.

The next group of 8 bits is just all 1’s so it’s 255.

Let’s see the third group of 8 bits:

01001101
11111000

01001000 = 72

The last octet (group of 8 bits) is all zeros so it’s just 0.

PING

Чтобы проверить этот показатель необходимо:

  1. Перейти в Пуск -> Все программы -> Стандартные -> Командная строка (или же Пуск -> Выполнить -> cmd).
  2. Далее “пропингуем” определенный IP-адрес, для этого необходимо ввести команду ping . Например, для пинга адреса 11.225.37.45 необходимо выполнить команду: ping 11.225.37.45
  3. Видим готовый результат.

Route Add Windows Command to Add Persistent Static Route in Windows 10

NSLOOKUP

Интуитивно понятно, что нужно будет ввести команду nslookup. В результате получаем:

Как сбросить сетевые настройки Windows 10

С командами, казалось, разобрались, но в результате что-то пошло не так и сеть вообще перестала работать? С такими процессами можно переборщить и приходится начинать настройку сетевых параметров с чистого листа, а для этого их нужно сбросить?

  • Шаг 1: Восстановить сетевые настройки можно через раздел «Сеть и Интернет» в «Настройках» (Win + I) в пункте «Состояние».

Route Add Windows Command to Add Persistent Static Route in Windows 10

  • Шаг 2: В конце появившегося списка возможностей необходимо найти «Сброс сети».

Route Add Windows Command to Add Persistent Static Route in Windows 10

  • Шаг 3: Сброс сетевых настроек Windows 10 удаляет и переустанавливает сетевые адаптер на ПК. По окончанию также может понадобиться снова установить сетевое программное обеспечение, такие так VPN-сервисы и др. Об этом Windows и предупреждает.
  • Шаг 4: «Сбросить сейчас».

Route Add Windows Command to Add Persistent Static Route in Windows 10

Совет! Если нет уверенности в собственных силах, лучше не рисковать и обратиться за помощью к специалистам. Также стоит убедиться, что проблема именно в ПК, а не провайдере или маршрутизаторе. Для этого нужно сравнить Интернет-соединения на разных устройствах.

NETSH

NETSH (Network Shell) переводится как «сетевая оболочка». С ней можно до мелочей настроить любой сетевой адаптер на ПК. Команда проникает в каждую «оболочку» сети – маршрутизацию, диагностику и т.д., а в них – все команды и подкоманды. Без NETSH невозможно настроить свою сеть должным образом.

:/>  Как очистить файл через cmd

Route Add Windows Command to Add Persistent Static Route in Windows 10

Сетевые настройки Windows 10

Каждое действие на ПК можно подогнать «под себя». Для того, чтоб разобраться в сетевых настройках Windows 10, не нужно проходить курсы программирования. Главное – вникнуть в суть проблемы, быть предельно внимательным при настройке и у вас обязательно все получится!

Route Add Windows Command to Add Persistent Static Route in Windows 10

Сетевые настройки Windows 10

Практически все процессы на Windows настраиваются через панель управления, но для контроля над сетью она предлагает не так много возможностей. Система гораздо шире, и чтобы охватить все её аспекты, нужно знать некоторые «лазейки». В этом поможет командная строка и несколько важных команд, с которыми домашняя сеть будет работать так, как того хочет пользователь.

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 результаты.
  • /? – получить справку о доступных командах.

Route Add Windows Command to Add Persistent Static Route in Windows 10

Сброс сети в настройках Windows 10

Начиная с обновления версии 1607 в Windows 10 появилась упрощённая возможность выполнить сброс протокола TCP/IP и настроек DNS, всего лишь нажав несколько кнопок.При этом не просто удаляются адреса и перезапускается сетевой адаптер — система переустанавливает драйвера и протоколы, возвращая их к изначальному состоянию. Проще говоря, Виндовс выполняет ряд достаточно серьёзных операций, за которые «компьютерный мастер» по вызову взял бы не меньше 1000 рублей — просто нажмите кнопку.

Route Add Windows Command to Add Persistent Static Route in Windows 10

Чтобы выполнить сброс сетевых параметров и настроек сетевых адаптеров в Windows 10, Нужно нажать кнопку Пуск и зайти в параметры системы, кликнув на кнопочку с шестерёнкой.

Находим значок «Сеть и Интернет». Кликаем на него и переходим вот в такое окно:

Route Add Windows Command to Add Persistent Static Route in Windows 10

В подразделе «Состояние» нужно прокрутить содержимое странички до конца. Там будет кнопочка Сброс сети. Нажмите на неё.

Route Add Windows Command to Add Persistent Static Route in Windows 10

Операционная система ещё раз спросить точно ли Вы желаете сейчас выполнить эти действия. Да, мы уверены и нажимаем на кнопку «Сбросить сейчас».
Ну а дальше можно расслабиться, сходить налить чайку — процедура займёт некоторое время, после чего ПК перезапустится. При первом соединении с сетью (проводная или WiFi — без разницы) Вы увидите вот такое сообщение:

Route Add Windows Command to Add Persistent Static Route in Windows 10

Система интересуется — общественная или частная у вас сеть. Для домашней сети кликаем на «Да». Сброс сети завершён — проверяем её работу!

Внимание! Во время выполнения описанного выше процесса полностью удаляются и устанавливаются заново все сетевые адаптеры. Если с ними ранее были какие-либо проблемы или присутствует их аппаратная неисправность, то скорее всего исправить это не удастся и неприятность снова повторится.

The Bottom Line

So we see that our IP address 10.255.77.167 belongs in the 10.255.72.0 network which is our network.

When the host and destination IP are in the same network routing is pretty easy.  You can send the data packet directly to the destination IP via the MAC address; however, if it’s on a different network then you need to send the packet to a network device that can find your network resource.

This device is called the default gateway: think of it as your gateway to the internet, it’s the doorway to getting off your local home network to the world wide web.

Using ROUTE PRINT and netstat -rn is useful because occasionally you’ll try every troubleshooting technique under the sun only to realize that your routing table has a corrupt entry or a key entry is missing.  These two commands are essential when troubleshooting network communication problems.

Don’t leave home without it lol.

Сброс параметров TCP/IP в командной строке

Если Вы не хотите переустанавливать драйверы и протоколы в системе, а нужно просто сбросить настройки IP и DNS, то в этом случае я бы рекомендовал воспользоваться возможностями командной строки и утилиты netsh (сокр. от network shell).

Указанные ниже команды просто возвращают настройки всех сетевых адаптеров к заводским, а так же удаляют все параметры, которые были выставлены программами, либо пользователями.

Что нужно делать? Начнём с того, что запустим командную строку с правами администратора. Для этого в Windows 10 надо кликнуть правой кнопкой мыши на кнопку «Пуск».

Route Add Windows Command to Add Persistent Static Route in Windows 10

Появится меню, где надо выбрать пункт «Командная строка (Администратор)» либо, как в моём случае, «Windows PowerShell (Администратор)». В нашем случае никакой разницы в этом нет.

Далее по очереди вводим команды:

После каждой строчки нажимаем клавишу Enter и ждём результата. По завершению выполнения всех команд — перезагрузите компьютер.

IPCONFIG

IPCONFIG помогает тогда, когда сеть в целом работает отлично, но доступ к некоторым ресурсам всё так же закрыт. Команда информативна и поэтому не быстрая, но работает с несколькими ключами для выполнения других команд. Она показывает все сетевые адаптеры на ПК и уровень их работы.

Тут можно также вводить разные параметры после команды ipconfig, такие как:

  • /? – отобразить справку непосредственно в самой командной строке.
  • /all – полная конфигурация TCP/IP для всех адаптеров. Без этого параметра команда ipconfig выводит только IP-адреса, маску подсети и основной шлюз для каждого адаптера.
  • /release [адаптер] – отправить сообщение DHCPRELEASE серверу DHCP, чтобы освободить текущую конфигурацию DHCP и удалить конфигурацию IP-адресов для всех или для одного адаптеров (если он не задан). Мы можем отключить протокол TCP/IP для адаптеров, настроенных для автоматического получения IP-адресов. Чтобы указать адаптер, введите без параметров имя, выводимое командой ipconfig.
  • /flushdns – Сброс и очистка содержимого кэша сопоставления имен DNS клиента. Во время устранения неполадок DNS эту процедуру используют для удаления из кэша записей отрицательных попыток сопоставления и других динамически добавляемых записей.
  • /displaydns – показывает содержимое кэша сопоставления имен DNS клиента, включая записи, предварительно загруженные из локального файла Hosts и записи ресурсов (последние) для запросов на сопоставление имен. Всю эту информацию использует служба DNS клиента для быстрого сравнения часто встречаемых имен без обращения к указанным в конфигурации DNS-серверам.
  • /registerdns – ручная динам. регистрация DNS имя и IP-адреса, которые настроены на ПК. Можно задавать этот параметр когда нужно устранить неполадки в случае отказа в регистрации имени DNS или при сбое динамического обновления между клиентом и DNS-сервером без перезагрузки клиента. Имена, зарегистрированные в DNS, характеризуются параметрами DNS в дополнительных свойствах протокола TCP/IP.
  • /showclassid адаптер – на экране отобразиться код класса DHCP для указанного адаптера. Чтобы просмотреть код класса DHCP для всех адаптеров, вместо адаптер в команде нужно указать (*). Команда будет работать только на тех ПК, где установлены адаптеры, настроенные на автоматическое получение IP.
  • /setclassid адаптер [код_класса] – можем задать код класса DHCP для указанного адаптера. Чтобы это сделать сразу для всех адаптеров, вместо адаптер указываем (*). То же условие работоспособности, что и для предыдущей команды. Код класса DHCP не задан? Значит текущий будет удален.

Route Add Windows Command to Add Persistent Static Route in Windows 10

Как удалённо очистить таблицу маршрутов

Если вы хотите проделать все эти операции удалённо, вам понадобится программа NetAdapter Repair (подробнее). Дело в том, что после применения команды route -f соединение с сервером будет утрачено. А утилита NetAdapter Repair автоматически перезагрузит компьютер после очистки таблицы маршрутов. Для удалённой очистки необходимо проделать следующие действия:

1 Запустить утилиту NetAdapter Repair от имени Администратора.

2 Установить флажок возле пункта Clear ARP/Route Table.

3 Нажать кнопку Run All Selected:

Route Add Windows Command to Add Persistent Static Route in Windows 10

После выполнения операции пойдёт обратный отсчёт времени и компьютер (сервер) перезагрузится автоматически:

Route Add Windows Command to Add Persistent Static Route in Windows 10

Если что-то непонятно, спрашивайте в комментариях.

Оставьте комментарий