Команда ROUTE — Обработка таблиц сетевых маршрутов.
Формат командной строки:
ROUTE [-f] [-p] [-4|-6] command [destination] [MASK netmask] [gateway] [METRIC metric] [IF interface]
Подсказку по параметрам командной строки можно получить используя встроенную справку ( route /? ):
-f — Очистка таблиц маршрутов от записей всех шлюзов. При указании одной из команд таблицы очищаются до выполнения команды.
-p — При использовании с командой ADD задает сохранение маршрута при перезагрузке системы. По умолчанию маршруты не сохраняются при перезагрузке. Пропускается для остальных команд, изменяющих соответствующие постоянные маршруты. Этот параметр не поддерживается в Windows 95.
-4 — Обязательное использование протокола IPv4.
-6 — Обязательное использование протокола IPv6.
command — Одна из следующих команд:
— PRINT — Печать маршрута
— ADD — Добавление маршрута
— DELETE — Удаление маршрута
— CHANGE — Изменение существующего маршрута
destination — Адресуемый узел.
MASK — Указывает, что следующий параметр интерпретируется как маска сети.
netmask — Значение маски подсети для записи данного маршрута. Если этот параметр не задан, по умолчанию используется значение 255.255.255.255.
interface — Номер интерфейса для указанного маршрута.
METRIC — Определение метрики, т.е. цены для адресуемого узла. Чем ниже значение метрики, тем выше приоритет узла при построении маршрута.
Поиск всех символических имен узлов проводится в файле сетевой базы данных NETWORKS. Поиск символических имен шлюзов проводится в файле базы данных имен узлов HOSTS.
Для команд PRINT и DELETE можно указать узел и шлюз с помощью подстановочных знаков или опустить параметр «шлюз».
Если адресуемый узел содержит подстановочные знаки * или ?, он используется в качестве шаблона, и печатаются только соответствующие ему маршруты. Знак ‘*’ соответствует любой строке, а ‘?’ — одному знаку.
Примеры: 157.*.1, 157.*, 127.*, *224*.
Соответствие шаблону поддерживает только команда PRINT.
Недопустимое значение MASK вызывает ошибку, если (УЗЕЛ & МАСКА) != УЗЕЛ.
Например:
route ADD 157.0.0.0 MASK 155.0.0.0 157.55.80.1 IF 1 — Добавление маршрута завершится ошибкой, поскольку указан недопустимый параметр маски. (Узел & Маска) != Узел.
route PRINT — отобразить таблицу маршрутов
route PRINT -4 — отобразить таблицу маршрутов только для IPv4
route PRINT -6 — отобразить таблицу маршрутов только для IPv6
route PRINT 157* — отобразить таблицу маршрутов только для узлов, начинающихся со 157
Если сетевой интерфейс (IF) не задан, то производится попытка найти лучший интерфейс для указанного шлюза.
route ADD 3ffe::/32 3ffe::1 — добавить новый маршрут для узла с IPv6
route CHANGE 157.0.0.0 MASK 255.0.0.0 157.55.80.5 METRIC 2 IF 2 — изменить существующий маршрут для узла IPv4
Параметр CHANGE используется только для изменения шлюза или метрики.
route DELETE 157.0.0.0 — удалить маршрут для IPv4.
route DELETE 3ffe::/32 — удалить маршрут для IPV6
Примеры использования команды ROUTE
route print — отобразить текущую таблицу маршрутов.
Пример отображаемой таблицы:
===========================================================================
Список интерфейсов
24. 00 50 ba 5d 0c c4 . D-Link DFE-538TX 10/100 адаптер
13. 00 19 db ce 97 9c . Сетевая карта Realtek RTL8169/8110 Family NIC
1. Software Loopback Interface 1
17. 00 00 00 00 00 00 00 e0 Адаптер Microsoft ISATAP
12. 00 00 00 00 00 00 00 e0 Teredo Tunneling Pseudo-Interface
===========================================================================
IPv4 таблица маршрута
===========================================================================
Активные маршруты:
Сетевой адрес 0.0.0.0 127.0.0.0 . 224.0.0.0 | Маска сети 0.0.0.0 255.0.0.0 . 240.0.0.0 | Адрес шлюза 192.168.0.1 On-link . On-link | Интерфейс 192.168.0.2 127.0.0.1 . 192.168.0.2 | Метрика 266 306 . 266 |
===========================================================================
Постоянные маршруты:
Сетевой адрес 0.0.0.0 | Маска 0.0.0.0 | Адрес шлюза 192.168.0.1 | Метрика По умолчанию |
===========================================================================
IPv6 таблица маршрута
===========================================================================
Активные маршруты:
Метрика 1 40 19 20 20 1 | Сетевой адрес 306 ::1/128 276 fe80::/64 276 fe80::/64 276 fe80::/64 276 fe80::6034:c4a3:8e4e:b7a 306 ff00::/8 | Шлюз On-link On-link On-link On-link a/128 On-link /128 On-link 7/128 On-link On-link On-link On-link On-link |
===========================================================================
Постоянные маршруты:
Отсутствует
Список интерфейсов — отображаются идентификаторы ( ID ), физические ( MAC ) адреса и названия сетевых адаптеров. В примере:
24 — идентификатор интерфейса
00 50 ba 5d 0c c4 — MAC-адрес сетевого адаптера
D-Link DFE-538TX 10/100 адаптер — название сетевого адаптера.
Сетевой адрес (Network Destination) — IP-адрес, адрес сети, или адрес 0.0.0.0 используемый для шлюза по умолчанию ( Default Gateway ). Это конечная точка маршрута
Маска сети ( Netmask ) — маска сети.
Адрес шлюза ( Gateway ) — IP-адрес шлюза, через который будет выполняться отправка пакета для достижения конечной точки.
В Windows Vista / Windows 7 / 8 и более поздних версиях, для адресов, достижимых локально, в данной колонке отображается On-link . Другими словами, значение On-link в колонке «Шлюз» означает, что шлюз не используется, адрес назначения достижим напрямую, без маршрутизации.
Интерфейс ( Interface ) — IP-адрес сетевого интерфейса, через который выполняется доставка пакета конечной точке маршрута.
Метрика ( metric ) — значение метрики (1-9999). Метрика представляет собой числовое значение, позволяющее оптимизировать доставку пакета получателю, если конечная точка маршрута может быть достижима по нескольким разным маршрутам. Чем меньше значение метрики, тем выше приоритет маршрута.
route print 192.* — отобразить таблицу маршрутов только для адресов, начинающихся с 192.
route add 0.0.0.0 mask 0.0.0.0 192.168.1.1 — установить в качестве шлюза по умолчанию (основного шлюза) адрес 192.168.1.1
route -p add 10.0.0.0 mask 255.0.0.0 10.0.0.1 — добавить маршрут для подсети 10.0.0.0/255.0.0.0 и запомнить его в реестре . Это постоянный статический маршрут. Если маршрут добавлен без использования параметра -p то он сохраняется только до перезагрузки системы (до перезапуска сетевого системного программного обеспечения). Если же, при добавлении маршрута искользовался данный параметр, то информация о маршруте записывается в реестр Windows (раздел HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\PersistentRoutes ) и будет использоваться постоянно при активации сетевых интерфейсов.
route delete 10.0.0.0 mask 255.0.0.0 — удалить маршрут для подсети 10.0.0.0/255.0.0.0 .
route add 10.10.10.10 192.168.1.158 — добавить маршрут для узла с IP-адресом 10.10.10.10 . Если маска в команде не задана, то подразумевается ее значение равное 255.255.255.255 , т.е конечная точка назначения является одиночным IP-адресом узла.
route delete 10.10.10.10 — удалить маршрут созданный предыдущей командой
route change 10.0.0.0 mask 255.0.0.0 10.10.10.1 — изменить адрес шлюза для существующего маршрута к сети 10.0.0.0/255.0.0.0 на значение 10.10.10.1 Допускается использование данной команды только для изменения адреса шлюза и метрики.
route -f — очистить таблицу маршрутов. После перезагрузки системы, или при перезапуске сетевых подключений таблица маршрутов будет восстановлена исходя из текущей сетевой конфигурации компьютера. При выполнении команды route -f из таблицы удаляются все маршруты, которые удовлетворяют условиям:
— не относятся к петлевому интерфейсу ( интерфейсу с IP 127.0.0.1 и маской -255.0.0.0)
— не являются маршрутами для многоадресной (multicast) рассылки (IP 224.0.0.1 маска 255.0.0.0)
— не являются узловыми маршрутами (когда маска равна 255.255.255.255) .
При обработке таблицы маршрутов, статические маршруты имеют высший приоритет, по сравнению с маршрутом, использующим для достижения конечной точки шлюз по умолчанию.
Если вы желаете поделиться ссылкой на эту страницу в своей социальной сети, пользуйтесь кнопкой «Поделиться»
Route
Applies To: Windows Server 2003, Windows Vista, Windows XP, Windows Server 2008, Windows 7, Windows Server 2003 R2, Windows Server 2008 R2, Windows Server 2000, Windows Server 2012, Windows 8
Displays and modifies the entries in the local IP routing table. Used without parameters, route displays help. For examples of how this command can be used, see Examples.
Syntax
Parameters
Clears the routing table of all entries that are not host routes (routes with a netmask of 255.255.255.255), the loopback network route (routes with a destination of 127.0.0.0 and a netmask of 255.0.0.0), or a multicast route (routes with a destination of 224.0.0.0 and a netmask of 240.0.0.0). If this is used in conjunction with one of the commands (such as add, change, or delete), the table is cleared prior to running the command.
When used with the add command, the specified route is added to the registry and is used to initialize the IP routing table whenever the TCP/IP protocol is started. By default, added routes are not preserved when the TCP/IP protocol is started. When used with the print command, the list of persistent routes is displayed. This parameter is ignored for all other commands. Persistent routes are stored in the registry location HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\PersistentRoutes.
Specifies the command you want to run. The following lists valid commands:
add: Adds a route.
change: Modifies an existing route.
delete: Deletes a route or routes.
print: Prints a route or routes.
Specifies the network destination of the route. The destination can be an IP network address (where the host bits of the network address are set to 0), an IP address for a host route, or 0.0.0.0 for the default route.
Specifies the network destination of the route. The destination can be an IP network address (where the host bits of the network address are set to 0), an IP address for a host route, or 0.0.0.0 for the default route.
Specifies the forwarding or next hop IP address over which the set of addresses defined by the network destination and subnet mask are reachable. For locally attached subnet routes, the gateway address is the IP address assigned to the interface that is attached to the subnet. For remote routes, available across one or more routers, the gateway address is a directly reachable IP address that is assigned to a neighboring router.
Specifies an integer cost metric (ranging from 1 to 9999) for the route, which is used when choosing among multiple routes in the routing table that most closely match the destination address of a packet being forwarded. The route with the lowest metric is chosen. The metric can reflect the number of hops, the speed of the path, path reliability, path throughput, or administrative properties.
Specifies the interface index for the interface over which the destination is reachable. For a list of interfaces and their corresponding interface indexes, use the display of the route print command. You can use either decimal or hexadecimal values for the interface index. For hexadecimal values, precede the hexadecimal number with 0x. When the if parameter is omitted, the interface is determined from the gateway address.
Displays Help at the command prompt.
Remarks
Large values in the metric column of the routing table are the result of allowing TCP/IP to automatically determine the metric for routes in the routing table based on the configuration of IP address, subnet mask, and default gateway for each LAN interface. Automatic determination of the interface metric, enabled by default, determines the speed of each interface and adjusts the metrics of routes for each interface so that the fastest interface creates the routes with the lowest metric. To remove the large metrics, disable the automatic determination of the interface metric from the advanced properties of the TCP/IP protocol for each LAN connection.
Names can be used for Destination if an appropriate entry exists in the local Networks file stored in the **systemroot\System32\Drivers\**Etc folder. Names can be used for the gateway as long as they can be resolved to an IP address through standard host name resolution techniques such as Domain Name System (DNS) queries, use of the local Hosts file stored in the **systemroot\system32\drivers\**etc folder, and NetBIOS name resolution.
If the command is print or delete, the Gateway parameter can be omitted and wildcards can be used for the destination and gateway. The Destination value can be a wildcard value specified by an asterisk (*). If the destination specified contains an asterisk (*) or a question mark (?), it is treated as a wildcard and only matching destination routes are printed or deleted. The asterisk matches any string, and the question mark matches any single character. For example, 10.*.1, 192.168.*, 127.*, and *224* are all valid uses of the asterisk wildcard.
Using an invalid combination of a destination and subnet mask (netmask) value displays a «Route: bad gateway address netmask» error message. This error message appears when the destination contains one or more bits set to 1 in bit locations where the corresponding subnet mask bit is set to 0. To test this condition, express the destination and subnet mask using binary notation. The subnet mask in binary notation consists of a series of 1 bits, representing the network address portion of the destination, and a series of 0 bits, representing the host address portion of the destination. Check to determine whether there are bits in the destination that are set to 1 for the portion of the destination that is the host address (as defined by the subnet mask).
The /p parameter is only supported on the route command for WindowsВ NTВ 4.0, WindowsВ 2000, WindowsВ MillenniumВ Edition, WindowsВ XP, and Windows ServerВ 2003. This parameter is not supported by the route command for WindowsВ 95 or WindowsВ 98.
This command is available only if the Internet Protocol (TCP/IP) protocol is installed as a component in the properties of a network adapter in Network Connections.
Examples
To display the entire contents of the IP routing table, type:
To display the routes in the IP routing table that begin with 10, type:
To add a default route with the default gateway address of 192.168.12.1, type:
To add a route to the destination 10.41.0.0 with the subnet mask of 255.255.0.0 and the next hop address of 10.27.0.1, type:
To add a persistent route to the destination 10.41.0.0 with the subnet mask of 255.255.0.0 and the next hop address of 10.27.0.1, type:
To add a route to the destination 10.41.0.0 with the subnet mask of 255.255.0.0, the next hop address of 10.27.0.1, and the cost metric of 7, type:
To add a route to the destination 10.41.0.0 with the subnet mask of 255.255.0.0, the next hop address of 10.27.0.1, and using the interface index 0x3, type:
To delete the route to the destination 10.41.0.0 with the subnet mask of 255.255.0.0, type:
To delete all routes in the IP routing table that begin with 10, type:
To change the next hop address of the route with the destination of 10.41.0.0 and the subnet mask of 255.255.0.0 from 10.27.0.1 to 10.27.0.25, type: