Route add if windows пример

Маршрутизация в Windows

Маршрутизация в Windows

Маршрутизация – это процесс передачи IP-трафика адресатам в сети, то есть процесс передачи пакетов от хоста-источника к  хосту-адресату через промежуточные маршрутизаторы. Изучая эту статью предполагается что вы изучили материал основы компьютерных сетей.

Изучим как работает маршрутизация в Windows, что бы понять как она работает, а не просто прочитать и забыть, вам необходимо несколько виртуальных машин, а именно:

  • ВМ с Windows XP.
  • 2 ВМ с Windows Server 2003.

Учтите, что при настройке виртуальных машин, в настройках сети нужно указать «Внутренняя сеть» и задать одинаковое имя сети для всех машин.

Если вы не поленитесь и установите три виртуальные машины, а так же изучите этот материал до конца, то у вас будет практическое понимание работы сети в операционных системах семейства Windows.

Содержание:

  • Таблица маршрутизации
  • Статическая маршрутизация
  • Маршрутизация по умолчанию
  • Динамическая маршрутизация, протокол RIP

Для простоты передачи данных хост-источник и маршрутизатор принимают решения о передаче пакетов на основе своих таблиц IP-маршрутизации. Записи таблицы создаются при помощи:

  1. Программного обеспечения стека TCP/IP.
  2. Администратора, путем конфигурирования статических маршрутов.
  3. Протоколов маршрутизации, одним из которых является протокол передачи маршрутной информации – RIP.

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

Пример маршрутизации в Windows

Допустим, у нас есть три узла:

  • Windows XP.
  • Windows Server 2003 – 1.
  • Windows Server 2003 – 2.

Хост XP имеет один сетевой адаптер (интерфейс) с IP-адресом 192.168.0.2 и маской подсети 255.255.255.0. Маршрутизатор Server1 имеет два интерфейса с IP-адресами 192.168.0.1 и 192.168.1.1 и масками подсети 255.255.255.0. Маршрутизатор Server2 также имеет 2 сетевых адаптера с IPадресами 192.168.1.2 и 192.168.2.1 и масками подсети 255.255.255.0. Таким образом, мы имеем 3 сети: сеть с IP-адресом 192.168.0.0 (Net 1), сеть с IP-адресом 192.168.1.0 (Net 2), сеть с IP-адресом 192.168.2.0 (Net 3).

Схема сети

Таблица маршрутизации

Таблица маршрутизации по умолчанию создается на узле автоматически с помощью программного обеспечения стека TCP/IP.

При настройке сетевого подключения на хосте XP были статически заданы IP-адрес 192.168.0.2 и маска подсети 255.255.255.0, основной шлюз задан не был. Программное обеспечение стека TCP/IP автоматически создало таблицу маршрутизации по умолчанию.

Что бы просмотреть таблицы маршрутизации на узле XP выполним команду route print в командной строке (Пуск -> Выполнить -> cmd).

Простая таблица маршрутизации

Таблица маршрутизации содержит для каждой записи следующие поля: Сетевой адрес (Network Destination), Маска сети (Netmask), Адрес шлюза (Gateway), Интерфейс (Interface) и Метрика (Metric). Разберем каждое поле подробнее.

Сетевой адрес. Поле определяет диапазон IP-адресов достижимых с использованием данной таблицы.

Маска сети. Битовая маска, которая служит для определения значащих разрядов в поле Сетевой адрес. Маска состоит из непрерывных единиц и нулей, отображается в десятичном коде. Поля Сетевой адрес и Маска определяют один или несколько IP-адрес.

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

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

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

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

  • с помощью статических маршрутов;
  • с помощью маршрутов по умолчанию;
  • с помощью маршрутов, определенных протоколами динамической маршрутизации.

Рассмотрим каждый из способов по порядку.

Статическая маршрутизация

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

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

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

Но вернемся к нашему примеру. Наша задача, имя исходные данные, установить соединения между хостом XP и Server2 который находится в сети Net3, то есть нужно что бы проходил пинг на 192.168.2.1.

Начнем выполнять на хосте XP команды ping постепенно удаляясь от самого хоста. Выполните в Командной строке команды ping для адресов 192.168.0.2, 192.168.0.1, 192.168.1.1.

Мы видим, что команды ping по адресу собственного интерфейса хоста XP и по адресу ближайшего интерфейса соседнего маршрутизатора Server1 выполняются успешно.

Пинг узла на себя

Пинг на Server1

Однако при попытке получить ответ от второго интерфейса маршрутизатора Server1 выводится сообщение «Заданный узел недоступен» или «Превышен интервал ожидания для запроса».

Пинг на сервер 2

Это связано с тем, что в таблице маршрутизации по умолчанию хоста XP имеются записи о маршруте к хосту 192.168.0.2 и о маршруте к сети 192.168.0.0, к которой относится интерфейс маршрутизатора Server1 с адресом 192.168.0.1. Но в ней нет записей ни о маршруте к узлу 192.168.1.1, ни о маршруте к сети 192.168.1.0.

Добавим в таблицу маршрутизации XP запись о маршруте к сети 192.168.1.0. Для этого введем команду route add с необходимыми параметрами:

route add [адресат] [mask маска] [шлюз] [metric метрика] [if интерфейс]

Параметры команды имеют следующие значения:

  • адресат — адрес сети или хоста, для которого добавляется маршрут;
  • mask — если вводится это ключевое слово, то следующий параметр интерпретируется как маска подсети, соответственно маска — значение маски;
  • шлюз — адрес шлюза;
  • metric — после этого ключевого слова указывается метрика маршрута до адресата (метрика);
  • if — после этого ключевого слова указывается индекс интерфейса, через который будут направляться пакеты заданному адресату.

Индекс интерфейса можно определить из секции Список интерфейсов (Interface List) выходных данных команды route print.

Выполним команду route print.

Команда route print

Теперь мы видим , что хост XP имеет два интерфейса: логический интерфейс замыкания на себя (Loopback) и физический интерфейс с сетевым адаптером Intel(R) PRO/1000. Индекс физического интерфейса – 0x2.

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

route add 192.168.1.0 mask 255.255.255.0 192.168.0.1 metric 2 if 0x2

Данная команда сообщает хосту XP о том, что для того, чтобы достичь сети 192.168.1.0 с маской 255.255.255.0, необходимо использовать шлюз 192.168.0.1 и интерфейс с индексом 0x2, причем сеть 192.168.1.0 находится на расстоянии двух транзитных участка от хоста XP.

Выполним пинг на 192.168.1.1 и убедимся, что связь есть.

Продолжим пинговать серверы, теперь проверьте отклик от второго маршрутизатора, присоединенного к сети Net2 (Server2). Он имеет IP-адрес 192.168.1.2.

Получаем сообщение «Превышен интервал ожидания запроса». В данном случае это означает что наш хост XP знает как отправлять данные адресату, но он не получает ответа.

Это происходит по тому, что хост Server2 не имеет информации о маршруте до хоста 192.168.0.1 и до сети 192.168.0.0 соответственно, поэтому он не может отправить ответ.

Для этого необходимо выполнить команду route add с соответствующими параметрами, однако сначала необходимо узнать индекс интерфейса с адресом 192.168.1.2.

На Server2 выполним команду route print и посмотрим индекс первого физического интерфейса. Далее, с помощью команды route add добавьте на Server2 маршрут до сети Net1, аналогично тому, как мы добавляли маршрут хосту XP.
В моем случае это команда:

route add 192.168.0.0 mask 255.255.255.0 192.168.1.1 metric 2 if 0x10003

0x10003 — это индекс физического интерфейса сервера 2.

Индекс физического интерфейса

Индекс физического интерфейса может быть разным, обязательно обращайте на него внимание.

После того, как удостоверитесь в наличии связи между узлами XP и Server2, выполните команду ping 192.168.2.1, т.е. проверьте наличие маршрута узла XP до сети Net3 (192.168.2.1 – IP-адрес маршрутизатора Server2 в сети Net3).

Вместо ответа вы получите сообщение «Заданный узел недоступен». С этой проблемой мы сталкивались еще в самом начале лабораторной работы, машина XP не знает путей до сети 192.168.2.0.

Добавьте в таблицу маршрутизации хоста XP запись о маршруте к сети 192.168.2.0. Это можно сделать путем ввода в командной строке хоста XP команды route add с соответствующими параметрами:

route add 192.168.2.0 mask 255.255.255.0 192.168.0.1 metric 3 if 0x2

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

Маршрутизация по умолчанию

Второй способ настройки маршрутизации в Windows — то маршрутизация по умолчанию.

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

Для добавления такого маршрута на хосте XP выполните следующую команду:

route add 0.0.0.0 mask 0.0.0.0 192.168.0.1 metric 2 if 0x10003

Эта команда сообщает хосту XP о том, что для того, чтобы достичь любой сети, маршрут к которой отсутствует в таблице маршрутизации, необходимо использовать шлюз 192.168.0.1 и интерфейс с индексом 0x10003.

Это так называемый маршрут по умолчанию.

Проверьте работоспособность с помощью команды ping.

Динамическая маршрутизация, протокол RIP

Протокол RIP (Routing Information Protocol или Протокол передачи маршрутной информации) является одним из самых распространенных протоколов динамической маршрутизации.

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

Есть две версии протокола RIP. Версия 1 не поддерживает маски, поэтому между сетями распространяется только информация о сетях и расстояниях до них. При этом для корректной работы RIP на всех интерфейсах всех маршрутизаторов составной сети должна быть задана одна и та же маска.

Протокол RIP полностью поддерживается только серверной операционной системой, тогда как клиентская операционная система (например, Windows XP) поддерживает только прием маршрутной информации от других маршрутизаторов сети, а сама передавать маршрутную информацию не может.

Настраивать RIP можно двумя способами:

  • В графическом режиме с помощью оснастки “Маршрутизация и удаленный доступ”.
  • В режиме командной строки с помощью утилиты netsh.

Рассмотрим настройку в режиме командной строки с помощью утилиты netsh.

Netsh – это утилита командной строки и средство выполнения сценариев для сетевых компонентов операционных систем семейства Windows (начиная с Windows 2000).

Введите в командной строке команду netsh, после появления netsh> введите знак вопроса и нажмите Enter, появиться справка по команде.

Введите последовательно команды:

  1. routing
  2. Ip
  3. rip
  4. ?

Вы увидите, что среди доступных команд этого контекста есть команда add interface, позволяющая настроить RIP на заданном интерфейсе. Простейший вариант этой команды – add interface «Имя интерфейса».

Если ввести в Windows XP в контексте netsh routing ip rip команду add interface "Net1", то получим сообщение «RIP должен быть установлен первым». Дело в том, что Установить RIP можно только в серверной операционной системе. В Windows Server 2003 в RIP включается в оснастке «Маршрутизация и удаленный доступ» (Пуск –> Программы –> Администрирование –> Маршрутизация и удаленный доступ). Таким образом, включить RIP в нашем случае можно только на маршрутизаторах Server1 и Server2.

Настроим RIP на Server1. Но сначала нужно выключит брандмауэр.

Теперь в оснастке «Маршрутизация и удаленный доступ» в контекстном меню пункта SERVER1 (локально) выберите пункт «Настроить и включить Маршрутизация ЛВС

Настроить и включить маршрутизацию и удаленный доступ

маршрутизацию и удаленный доступ».

В появившемся окне мастера нажмите «Далее».

Мастер установки сервера и удаленной маршрутизации

На следующем этапе выберите «Особая конфигурация» и нажмите «Далее».

Особая конфигурация

После чего нужно выбрать «Маршрутизация ЛВС» и завершить работу мастера.

Маршрутизация ЛВС

То же самое нужно выполнить на Server2.

Настройка через оснастку

В контекстном меню вкладки «Общие» (SERVER1 –> IP-маршрутизация –> Общие) нужно выбрать пункт «Новый протокол маршрутизации».

Новый протокол маршрутизации

Затем выделяем строку «RIP версии 2 для IP».

В контекстном меню появившейся вкладки «RIP» выберите «Новый интерфейс». Выделите строку «Подключение по локальной сети» и нажмите ОК.

Новый интерфейс RIP

Перед вами появиться окно.

Свойства интерфейса RIP

В появившемся окне необходимо задать следующие настройки:

  • Режим работы –> Режим периодического обновления.
  • Протокол для исходящих пакетов –> Для RIP версии 1.
  • Протокол входящих пакетов –> Только для RIP версии 1.

Оставьте оставшиеся настройки по умолчанию и нажмите ОК.

Далее необходимо выполнить эти действия для второго сетевого интерфейса.

После выполните те же действия для Sever2.

Проверьте, с помощью команды ping, работу сети.

Проверка работы сет ping

Поздравляю! Маршрутизация в Windows изучена.

The `route add` command in CMD is used to manually add a route to the local routing table, allowing you to specify the destination network, subnet mask, and gateway for packet routing.

route add <destination> MASK <subnet_mask> <gateway> [metric <metric>] [IF <interface_index>]

Replace `<destination>`, `<subnet_mask>`, `<gateway>`, `<metric>`, and `<interface_index>` with the specific values for your network configuration.

Understanding Networking Basics

What is Networking?

Networking refers to the practice of connecting computers and other devices to share resources and information. At the core of networking are components such as switches, routers, and protocols that work together to facilitate communication. Understanding basic networking concepts is essential as it provides the foundation for effectively managing and troubleshooting network connections.

What are Routes?

A route is a path that network packets follow to reach their destination. Routing enables data to travel across networks, guiding information on the most efficient paths. Configuring routes correctly is crucial for maintaining optimal network performance, minimizing latency, and ensuring reliable connectivity.

Mastering Ip Route Cmd: A Quick Reference Guide

Mastering Ip Route Cmd: A Quick Reference Guide

What is the `route` Command?

Introduction to the `route` Command

The `route` command is a tool available in Command Prompt (cmd) used to view and modify the IP routing table on a Windows operating system. The routing table holds essential information about how data packets should be directed through the network. Common use cases for the `route` command include adding, deleting, and modifying routing entries.

Syntax of the `route add` Command

The syntax for the `route add` command is as follows:

route ADD destination MASK subnet_mask gateway metric

This structure allows users to specify various parameters to define how the command should execute, detailing where the route leads and which gateway to utilize.

Trace Rout Cmd: Mastering Your Network Path in Cmd

Trace Rout Cmd: Mastering Your Network Path in Cmd

How to Use the `route add` Command

Basic Command Structure

To effectively use the `route add` command, it’s vital to understand the role of each parameter:

  • destination: This is the IP address or hostname of the target route. It represents where the data is intended to go.
  • subnet_mask: This defines the range of addresses contained in the destination network. A mask of `255.255.255.0` often indicates a class C subnet, usable for smaller networks.
  • gateway: This specifies the next-hop IP address through which packets will travel en route to the destination. It’s crucial that this address be reachable on the local network.
  • metric: An optional parameter that specifies the cost of using the route, allowing for priority between multiple routes.

Example of Basic Usage

Here’s an example of adding a basic route using the `route add` command:

route ADD 192.168.1.0 MASK 255.255.255.0 192.168.1.1

Explanation: The command above creates a route for the IP range `192.168.1.0` with a subnet mask of `255.255.255.0`, routing traffic through the gateway `192.168.1.1`. This command is particularly useful for directing packets within a local area network (LAN).

Mastering the Route Cmd Command in Minutes

Mastering the Route Cmd Command in Minutes

Advanced Routing Scenarios

Using Metrics

Importance of Metrics

Metrics play a vital role in route selection by indicating the “cost” associated with using a particular route. Lower metrics are preferred over higher ones. For instance, if you have two routes to the same destination, the system will choose the one with the lower metric.

Example Usage of Metrics

route ADD 10.0.0.0 MASK 255.255.255.0 10.0.0.1 METRIC 5

In this example, the command adds a route to the IP range `10.0.0.0` using `10.0.0.1` as the gateway, with a metric of `5`.

Adding Persistent Routes

What are Persistent Routes?

Persistent routes are routes that remain in the routing table even after a reboot. Having persistent routes can be beneficial for ensuring consistent and reliable routing configurations.

Command to Add a Persistent Route

To add a route that persists across reboots, use the `-p` switch:

route -p ADD 192.168.2.0 MASK 255.255.255.0 192.168.2.1

This command ensures that the route to `192.168.2.0` is maintained in the routing table after a system restart.

Mastering Cmd Route Print for Networking Insights

Mastering Cmd Route Print for Networking Insights

Viewing and Modifying Routes

Viewing the Current Routing Table

To view the routing table entries that are currently configured, the following command can be used:

route PRINT

This command provides a detailed list of all routes, including the destination, mask, gateway, and metric, allowing users to verify current configurations.

Modifying Existing Routes

If you need to change an existing route, use the `route CHANGE` command:

route CHANGE 192.168.1.0 MASK 255.255.255.0 192.168.1.254

This example modifies the route for `192.168.1.0`, directing traffic to a new gateway, `192.168.1.254`.

Deleting a Route

To delete a route from the routing table, you can use the `route DELETE` command:

route DELETE 192.168.1.0

This command effectively removes any route entries associated with `192.168.1.0`, ensuring that data packets will no longer be directed through that path.

Add User Cmd Windows 10: Your Quick Start Guide

Add User Cmd Windows 10: Your Quick Start Guide

Common Errors and Troubleshooting

Common Errors with `route add`

Users may encounter common errors when using the `route add` command, such as:

  • Mismatched subnet masks: Ensure that the subnet mask accurately represents the route being added.
  • Incorrect gateway address: Verify that the specified gateway is reachable; otherwise, packets will be dropped.

How to Troubleshoot with CMD

To troubleshoot routing issues, utilize cmd tools like `ping` and `tracert`. The `ping` command tests connectivity to a specific IP address, while the `tracert` command displays the route packets take to reach a destination, pinpointing any potential bottlenecks or failures.

Mastering The Startup Cmd: A Quick Guide

Mastering The Startup Cmd: A Quick Guide

Conclusion

The `add route cmd` command is an invaluable tool for effectively managing network configurations. By mastering how to add, modify, and delete routes, users can significantly enhance their network efficiency and reliability. Practice using these commands and explore further resources to deepen your understanding of command prompt functionalities related to networking.

Sometimes you need to manually add, change, or remove a route on a Windows machine. Here is quick guide to help you accomplish these tasks.

First start by opening a CMD prompt by going to start then typing cmd.

These commands should work for Win XP, Win Vista, Win 98, Win NT, Win 2000, Win 2008, Win 2012, Win 7, Win 8, Win 10.

Show the Current Routing Table

C:\>route print
===========================================================================
Interface List
 11...54 ee 75 5b e3 c9 ......Intel(R) Ethernet Connection (3) I218-LM
 13...5c e0 c5 7f e4 c8 ......Intel(R) Dual Band Wireless-AC 7265
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0   192.168.177.1    192.168.177.30     10
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    306
     192.168.60.0    255.255.255.0         On-link      192.168.60.1    276
     192.168.60.1  255.255.255.255         On-link      192.168.60.1    276
   192.168.60.255  255.255.255.255         On-link      192.168.60.1    276
    192.168.177.0    255.255.255.0         On-link     192.168.177.1    276
    192.168.177.1  255.255.255.255         On-link     192.168.177.1    276
  192.168.177.255  255.255.255.255         On-link     192.168.177.1    276
===========================================================================
Persistent Routes:
  None

The default route is represented by A destination/netmask of 0.0.0.0. If there isn’t a route with a more specific destination and netmask, the default route is used.

Use this subnet calculator if you need help subnetting.

Add a Static Route

To add a route to the routing table use the route add command. An example looks like this:

route add 10.0.0.0 mask 255.0.0.0 192.168.177.1

You can optionally add a metric 2 to the end if you want to add a specific weight to the route. The routes with the lowest metric will take precedence over higher metrics. By default, static routes have a metric of 6.

You can also optionally add a IF 2 to the end. This will force the route to use interface 2. You can see what interface numbers you have with the route print command.

Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
         10.0.0.0        255.0.0.0         On-link     172.16.177.30      6

Remove a Static Route

To remove a route you must use the route delete command and the destination.

route delete 10.0.0.0

Change a Static Route

If you simply want to update a static route you can use the route change command.

route CHANGE 157.0.0.0 MASK 255.0.0.0 157.55.80.5 METRIC 2 IF 2

Troubleshooting

If you get the following error:
The requested operation requires elevation.

To resolve this you will need administrator access to the system. Go to the start menu and when you type cmd right click on the cmd.exe program and click Run As Administrator. This opens a CMD prompt with more privileges.

For any further help you can use the built in help the route command provides. Simply type route and hit enter.

C:\>route

Manipulates network routing tables.

ROUTE [-f] [-p] [-4|-6] command [destination]
                  [MASK netmask]  [gateway] [METRIC metric]  [IF interface]

  -f           Clears the routing tables of all gateway entries.  If this is
               used in conjunction with one of the commands, the tables are
               cleared prior to running the command.

  -p           When used with the ADD command, makes a route persistent across
               boots of the system. By default, routes are not preserved
               when the system is restarted. Ignored for all other commands,
               which always affect the appropriate persistent routes. This
               option is not supported in Windows 95.

  -4           Force using IPv4.

  -6           Force using IPv6.

  command      One of these:
                 PRINT     Prints  a route
                 ADD       Adds    a route
                 DELETE    Deletes a route
                 CHANGE    Modifies an existing route
  destination  Specifies the host.
  MASK         Specifies that the next parameter is the 'netmask' value.
  netmask      Specifies a subnet mask value for this route entry.
               If not specified, it defaults to 255.255.255.255.
  gateway      Specifies gateway.
  interface    the interface number for the specified route.
  METRIC       specifies the metric, ie. cost for the destination.

All symbolic names used for destination are looked up in the network database
file NETWORKS. The symbolic names for gateway are looked up in the host name
database file HOSTS.

If the command is PRINT or DELETE. Destination or gateway can be a wildcard,
(wildcard is specified as a star '*'), or the gateway argument may be omitted.

If Dest contains a * or ?, it is treated as a shell pattern, and only
matching destination routes are printed. The '*' matches any string,
and '?' matches any one char. Examples: 157.*.1, 157.*, 127.*, *224*.

Pattern match is only allowed in PRINT command.
Diagnostic Notes:
    Invalid MASK generates an error, that is when (DEST & MASK) != DEST.
    Example> route ADD 157.0.0.0 MASK 155.0.0.0 157.55.80.1 IF 1
             The route addition failed: The specified mask parameter is invalid.
 (Destination & Mask) != Destination.

Examples:

    > route PRINT
    > route PRINT -4
    > route PRINT -6
    > route PRINT 157*          .... Only prints those matching 157*

    > route ADD 157.0.0.0 MASK 255.0.0.0  157.55.80.1 METRIC 3 IF 2
             destination^      ^mask      ^gateway     metric^    ^
                                                         Interface^
      If IF is not given, it tries to find the best interface for a given
      gateway.
    > route ADD 3ffe::/32 3ffe::1

    > route CHANGE 157.0.0.0 MASK 255.0.0.0 157.55.80.5 METRIC 2 IF 2

      CHANGE is used to modify gateway and/or metric only.

    > route DELETE 157.0.0.0
    > route DELETE 3ffe::/32

Check out this article for more cool Windows CLI commands.


Displays and modifies the entries in the local IP routing table. If used without parameters, route displays help at the command prompt.

Usage

ROUTE [-f] [-p] [-4|-6] command [destination]
                  [MASK netmask]  [gateway] [METRIC metric]  [IF interface]

Flags

  -f           Clears the routing tables of all gateway entries.  If this is
               used in conjunction with one of the commands, the tables are
               cleared prior to running the command.

  -p           When used with the ADD command, makes a route persistent across
               boots of the system. By default, routes are not preserved
               when the system is restarted. Ignored for all other commands,
               which always affect the appropriate persistent routes.

  -4           Force using IPv4.

  -6           Force using IPv6.

  command      One of these:
                 PRINT     Prints  a route
                 ADD       Adds    a route
                 DELETE    Deletes a route
                 CHANGE    Modifies an existing route
  destination  Specifies the host.
  MASK         Specifies that the next parameter is the 'netmask' value.
  netmask      Specifies a subnet mask value for this route entry.
               If not specified, it defaults to 255.255.255.255.
  gateway      Specifies gateway.
  interface    the interface number for the specified route.
  METRIC       specifies the metric, ie. cost for the destination.

All symbolic names used for destination are looked up in the network database
file NETWORKS. The symbolic names for gateway are looked up in the host name
database file HOSTS.

If the command is PRINT or DELETE. Destination or gateway can be a wildcard,
(wildcard is specified as a star '*'), or the gateway argument may be omitted.

If Dest contains a * or ?, it is treated as a shell pattern, and only
matching destination routes are printed. The '*' matches any string,
and '?' matches any one char. Examples: 157.*.1, 157.*, 127.*, *224*.

Pattern match is only allowed in PRINT command.
Diagnostic Notes:
    Invalid MASK generates an error, that is when (DEST & MASK) != DEST.
    Example> route ADD 157.0.0.0 MASK 155.0.0.0 157.55.80.1 IF 1
             The route addition failed: The specified mask parameter is invalid. (Destination & Mask) != Destination.

Examples:

    > route PRINT
    > route PRINT -4
    > route PRINT -6
    > route PRINT 157*          .... Only prints those matching 157*

    > route ADD 157.0.0.0 MASK 255.0.0.0  157.55.80.1 METRIC 3 IF 2
             destination^      ^mask      ^gateway     metric^    ^
                                                         Interface^
      If IF is not given, it tries to find the best interface for a given
      gateway.
    > route ADD 3ffe::/32 3ffe::1

    > route CHANGE 157.0.0.0 MASK 255.0.0.0 157.55.80.5 METRIC 2 IF 2

      CHANGE is used to modify gateway and/or metric only.

    > route DELETE 157.0.0.0
    > route DELETE 3ffe::/32

Examples

For more examples check learn.microsoft.com

Display the entire contents of the IP routing table

C:\Users\crypt0rr>route print
===========================================================================
Interface List
  9...00 1c 42 b0 90 e2 ......Parallels VirtIO Ethernet Adapter
 14...02 00 4c 4f 4f 50 ......Npcap Loopback Adapter
  1...........................Software Loopback Interface 1
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0      10.211.55.1      10.211.55.6     15
      10.211.55.0    255.255.255.0         On-link       10.211.55.6    271
      10.211.55.6  255.255.255.255         On-link       10.211.55.6    271
    10.211.55.255  255.255.255.255         On-link       10.211.55.6    271
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    331
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    331
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    331
      169.254.0.0      255.255.0.0         On-link    169.254.136.15    281
   169.254.136.15  255.255.255.255         On-link    169.254.136.15    281
  169.254.255.255  255.255.255.255         On-link    169.254.136.15    281
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    331
        224.0.0.0        240.0.0.0         On-link    169.254.136.15    281
        224.0.0.0        240.0.0.0         On-link       10.211.55.6    271
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    331
  255.255.255.255  255.255.255.255         On-link    169.254.136.15    281
  255.255.255.255  255.255.255.255         On-link       10.211.55.6    271
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
 If Metric Network Destination      Gateway
  1    331 ::1/128                  On-link
 14    281 fe80::/64                On-link
 14    281 fe80::2594:eebe:2b4d:880f/128
                                    On-link
  1    331 ff00::/8                 On-link
 14    281 ff00::/8                 On-link
===========================================================================
Persistent Routes:
  None

Display the routes in the IP routing table that begin with 10

C:\Users\crypt0rr>route print 10.*
===========================================================================
Interface List
  9...00 1c 42 b0 90 e2 ......Parallels VirtIO Ethernet Adapter
 14...02 00 4c 4f 4f 50 ......Npcap Loopback Adapter
  1...........................Software Loopback Interface 1
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
      10.211.55.0    255.255.255.0         On-link       10.211.55.6    271
      10.211.55.6  255.255.255.255         On-link       10.211.55.6    271
    10.211.55.255  255.255.255.255         On-link       10.211.55.6    271
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
  None
Persistent Routes:
  None

Add a default route with the default gateway address of 192.168.12.1

route add 0.0.0.0 mask 0.0.0.0 192.168.12.1

URL list

  • Learn.microsoft.com — route

add static route windows

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

The following is the general syntax of the route add command we need to follow to add a permanent static route in Windows:

route add -p <destination> mask <subnet-mask> <gateway>

For example, the following route command tells the windows to add a new persistent route to the 192.168.1.0/24 network, using 10.0.0.1 as the gateway to reach the network.

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.

For example, the following command adds a static route to the destination host 192.168.1.100 with the gateway address 10.0.0.1.

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

Following is another static route example with a metric value:

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

Windows hold permanent static routes in the following registry
location: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Servi
ces\Tcpip\Parameters\PersistentRoutes
.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Где найти средство просмотра фотографий windows 10
  • Canon raw codec for windows 10
  • Режима разработчика windows 10 что это
  • Kmod expansion not handled windows 10
  • Не найдены необходимые драйвера носителя при установке windows 10