To display the routing table on Windows, we can use route print
or netstat -r
command. The output of both commands is identical. However, the route
command has command options to filter the output to show the routing table for IPv4
or IPv6
separately.
To show the routing table, open a CDM (or PowerShell window) and type the following command:
route print
You will see an output similar to the following.
The output of the route print
command includes the following sections: Interface List, IPv4 Route Table, and IPv6 Route Table. The persistent Routes section shows permanent static routes.
Route Print Command Options
To show IPv4 routing table, Type:
route print -4
To show IPv6 routing table, Type:
route print -6
Using the wildcard character (*), you can create search patterns. For example route print 192.*
only prints those routes that have a destination IP address start with 192
.
Every computer on TCP/IP network (i.e. connect to Internet or LAN) depends on IP routing table to make routing decisions. Routing table, otherwise also known as Routing Information Base (RIB), is an electronic table (file) or database type object that is stored in a router or a networked computer to store the routes, and in some cases, metrics associated with those routes to particular network destinations, i.e. IP address.
Routing table is important for troubleshooting or identifying network problem, when all other components such as network cable, LAN connectivity, Ethernet (or FastEthernet or GigabitEthernet) port appear to have no error or issue. In rare cases, the routing table may point to incorrect interface to route, or has other routing problems, especially in the case of system with two or multiple NIC cards or network adapters.
To view, show or display the routing table in Windows or Linux (works on most Linux and Unix such as Ubuntu, RedHat, CentOS, etc.) operating system, use the following commands. In Windows, open a command prompt to issue the command:
netstat -rn
Alternatively, just type the following command in Linux:
route
Or, the following command in Windows XP, Windows Vista, Windows Server 2003, Windows Server 2008 and etc:
route print
In Windows Server based operating system, administrator can also view the content of routing table by using Routing And Remote Access GUI management console, accessible from Administrative Tools of Control Panel. After Configure and Enable Routing and Remote Access for LAN routing (under custom configuration), administrator can expand the node to view the routing table, and then expand IP Routing on the console tree. Then, right click on Static Routes and select Show IP Routing Table from the context menu. The entries in the routing table are displayed in the right pane of the Routing And Remote Access console.
The output or the routing table looks something similar with table below:
IPv4 Route Table =========================================================================== Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.2 25 127.0.0.0 255.0.0.0 On-link 127.0.0.1 306 127.0.0.1 255.255.255.255 On-link 127.0.0.1 306 127.255.255.255 255.255.255.255 On-link 127.0.0.1 306 192.168.1.0 255.255.255.0 On-link 192.168.1.2 281 192.168.1.2 255.255.255.255 On-link 192.168.1.2 281 192.168.1.255 255.255.255.255 On-link 192.168.1.2 281 224.0.0.0 240.0.0.0 On-link 127.0.0.1 306 224.0.0.0 240.0.0.0 On-link 192.168.1.2 281 255.255.255.255 255.255.255.255 On-link 127.0.0.1 306 255.255.255.255 255.255.255.255 On-link 192.168.1.2 281 ===========================================================================
Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 192.168.1.2 0.0.0.0 255.255.255.255 UH 0 0 0 eth1 10.10.10.1 0.0.0.0 255.255.255.192 U 0 0 0 eth0 192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1 10.0.0.0 10.14.42.129 255.0.0.0 UG 0 0 0 eth0 0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 eth1
Brief explanation and description of the columns in the routing table
Network destination or Destination: The destination host, subnet address, network address, or default route. The destination for a default route is 0.0.0.0.
Netmask or Genmask: The subnet mask that is applied to the destination IP address when matching it to the value in the network destination. Used in conjunction with the destination to determine when a route is used.
Gateway: The IP address that the local host uses to forward IP datagrams to other IP networks. This is either the IP address of a local network adapter or the IP address of an IP router (such as a default gateway router) on the local network segment.
Interface or iFace: The interface indicates the LAN or demand-dial interface (i.e. its IP address that is configured on the local computer for the local network adapter) that is to be used to reach the next router when an IP datagram is forwarded on the network.
Metric: Indicates the cost of using a route, which is typically the number of hops or the number of routers to cross to reach to the IP destination, Anything on the local subnet is one hop, and each router crossed after that is an additional hop. If there are multiple routes to the same destination with different metrics, the route with the lowest metric is the best route selected.
Protocol: Shows how the route was learned. If the Protocol column lists RIP, OSPF, or anything other than Local, then the router is receiving routes. Open Shortest Path First (OSPF) is not available on Windows XP 64-bit Edition (Itanium) and the 64-bit versions of the Windows Server 2003 family.
Flags: Describes the route with the following definitions – G (The route uses a gateway); U (The interface to be used is up); H (Only a single host can be reached through the route. For example, this is the case for the loopback entry 127.0.0.1); D (The route is dynamically created. It is set if the table entry has been generated by a routing daemon like gated or by an ICMP redirect message); M (The route is set if the table entry was modified by an ICMP redirect message) and ! (The route is a reject route and datagrams will be dropped).
MSS: Acronym for Maximum Segment Size, and is the size of the largest datagram the kernel will construct TCP connection for transmission via this route.
Window: Indicates the maximum amount of data the system will accept in a single burst from a remote host when establishing TCP connections.
irtt: Acronym for “initial round trip time” – indicates the value of time that the TCP protocol will use to wait for acknowledgment for a datagram to remote end has delivered been received when a connection is first established. The protocol is used to ensure reliability as hosts will retransmit a datagram if it has been lost (no ack received).
Each IP packet contains information about its origin and destination.
A routing table contains the information necessary to forward an IP packet along the best path toward its destination.
In this note i will show how to display the routing table in Windows using the route print
command.
Cool Tip: Check if TCP port is opened in PowerShell! Read more →
To display the routing table in Windows, use the route
command with the print
option.
Display all routing tables:
C:\> route print
Print IPv4 routing table:
C:\> route print -4
Print IPv6 routing table:
C:\> route print -6
Show only the network destinations that match 192*
:
C:\> route print 198*
Example of the routing table in Windows:
IPv4 Route Table ================================================================================== Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.31 50 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 192.168.1.0 255.255.255.0 On-link 192.168.1.31 306 192.168.1.31 255.255.255.255 On-link 192.168.1.31 306
Column | Description |
---|---|
Network Destination & Netmask | Specifies the pattern that a request must match with its destination address (IP address or CIDR range). |
Gateway | Specifies where to route a request i.e. the next hop to which the packet is to be sent on the way to its final destination. |
Interface | Indicates a local interface that is responsible for reaching the gateway. |
Metric | Indicates the associated cost of using the indicated route (“distance” to the target). In case of multiple feasible routes, the traffic will go through the gateway with the lowest metric. |
On-link
in the “Gateway” column means that the destination network is directly attached to the interface i.e. the NIC is in direct contact with the destination
network – on the same subnet.
The traffic that matches such route entry will trigger an ARP request on the interface to resolve the destination IP address directly i.e. find out a MAC-address of the target device (without contacting the gateway).
Cool Tip: How to show an ARP table and clear its cache in Windows! Read more →
Was it useful? Share this post with the world!
- 28.08.2020
- 65 349
- 3
- 30.01.2021
- 39
- 35
- 4
- Содержание статьи
- Описание
- Синтаксис
- Параметры
- Примеры
- Справочная информация
- Комментарии к статье ( 3 шт )
- Добавить комментарий
Описание
ROUTE — Выводит на экран и изменяет записи в локальной таблице IP-маршрутизации. Запущенная без параметров, команда route выводит справку.
Синтаксис
route [-f] [-p] [команда [конечная_точка] [mask маска_сети] [шлюз] [metric метрика]] [if интерфейс]]
Параметры
Параметр | Описание |
---|---|
-f | Очищает таблицу маршрутизации от всех записей, которые не являются узловыми маршрутами (маршруты с маской подсети 255.255.255.255), сетевым маршрутом замыкания на себя (маршруты с конечной точкой 127.0.0.0 и маской подсети 255.0.0.0) или маршрутом многоадресной рассылки (маршруты с конечной точкой 224.0.0.0 и маской подсети 240.0.0.0). При использовании данного параметра совместно с одной из команд (таких, как add, change или delete) таблица очищается перед выполнением команды |
-p | >При использовании данного параметра с командой add указанный маршрут добавляется в реестр и используется для инициализации таблицы IP-маршрутизации каждый раз при запуске протокола TCP/IP. По умолчанию добавленные маршруты не сохраняются при запуске протокола TCP/IP. При использовании параметра с командой print выводит на экран список постоянных маршрутов. Все другие команды игнорируют этот параметр. Постоянные маршруты хранятся в реестре по адресу HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\PersistentRoutes |
команда | Указывает команду, которая будет запущена на удаленной системе. Доступны следующие команды: add — Добавление маршрута change — Изменение существующего маршрута delete — Удаление маршрута или маршрутов print — Печать маршрута или маршрутов |
конечная_точка | Определяет конечную точку маршрута. Конечной точкой может быть сетевой IP-адрес (где разряды узла в сетевом адресе имеют значение 0), IP-адрес маршрута к узлу, или значение 0.0.0.0 для маршрута по умолчанию |
mask маска_сети | Указывает маску сети (также известной как маска подсети) в соответствии с точкой назначения. Маска сети может быть маской подсети соответствующей сетевому IP-адресу, например 255.255.255.255 для маршрута к узлу или 0.0.0.0. для маршрута по умолчанию. Если данный параметр пропущен, используется маска подсети 255.255.255.255. Конечная точка не может быть более точной, чем соответствующая маска подсети. Другими словами, значение разряда 1 в адресе конечной точки невозможно, если значение соответствующего разряда в маске подсети равно 0 |
шлюз | Указывает IP-адрес пересылки или следующего перехода, по которому доступен набор адресов, определенный конечной точкой и маской подсети. Для локально подключенных маршрутов подсети, адрес шлюза — это IP-адрес, назначенный интерфейсу, который подключен к подсети. Для удаленных маршрутов, которые доступны через один или несколько маршрутизаторов, адрес шлюза — непосредственно доступный IP-адрес ближайшего маршрутизатора |
metric метрика | Задает целочисленную метрику стоимости маршрута (в пределах от 1 до 9999) для маршрута, которая используется при выборе в таблице маршрутизации одного из нескольких маршрутов, наиболее близко соответствующего адресу назначения пересылаемого пакета. Выбирается маршрут с наименьшей метрикой. Метрика отражает количество переходов, скорость прохождения пути, надежность пути, пропускную способность пути и средства администрирования |
if интерфейс | Указывает индекс интерфейса, через который доступна точка назначения. Для вывода списка интерфейсов и их соответствующих индексов используйте команду route print. Значения индексов интерфейсов могут быть как десятичные, так и шестнадцатеричные. Перед шестнадцатеричными номерами вводится 0х. В случае, когда параметр if пропущен, интерфейс определяется из адреса шлюза |
/? | Отображает справку в командной строке |
Примечания:
- Большие значения в столбце
metric
таблицы маршрутизации — результат возможности протокола TCP/IP автоматически определять метрики маршрутов таблицы маршрутизации на основании конфигурации IP-адреса, маски подсети и стандартного шлюза для каждого интерфейса ЛВС. Автоматическое определение метрики интерфейса, включенное по умолчанию, устанавливает скорость каждого интерфейса и метрики маршрутов для каждого интерфейса так, что самый быстрый интерфейс создает маршруты с наименьшей метрикой. Чтобы удалить большие метрики, отключите автоматическое определение метрики интерфейса в дополнительных свойствах протокола TCP/IP для каждого подключения по локальной сети. - Имена могут использоваться для параметра конечная_точка, если существует соответствующая запись в файле базы данных Networks, находящемся в папке системный_корневой_каталог\System32\Drivers\Etc. В параметре шлюз можно указывать имена до тех пор, пока они разрешаются в IP-адреса с помощью стандартных способов разрешения узлов, таких как запрос службы DNS, использование локального файла Hosts, находящегося в папке системный_корневой_каталог\system32\drivers\etc, или разрешение имен NetBIOS.
- Если команда —
print
илиdelete
, параметр шлюз опускается и используются подстановочные знаки для указания точки назначения и шлюза. Значение конечной_точки может быть подстановочным значением, которое указывается звездочкой (*). При наличии звездочки (*) или вопросительного знака (?) в описании конечной точки, они рассматриваются как подстановки, тогда печатаются или удаляются только маршруты, соответствующие точке назначения. Звездочка соответствует любой последовательности символов, а вопросительный знак — любому одному символу. 10.*.1, 192.168.*, 127.* и *224* являются допустимыми примерами использования звездочки в качестве подстановочного символа. - При использовании недопустимой комбинации значений конечной точки и маски подсети (маски сети) выводится следующее сообщение об ошибке : «Маршрут: неверная маска подсети адреса шлюза». Ошибка появляется, когда одно или несколько значений разрядов в адресе конечной точки равно 1, а значения соответствующих разрядов маски подсети — 1. Для проверки этого состояния выразите конечную точку и маску подсети в двоичном формате. Маска подсети в двоичном формате состоит из последовательности единичных битов, представляющей часть сетевого адреса конечной точки, и последовательности нулевых битов, обозначающей часть адреса узла конечной точки. Проверьте наличие единичных битов в части адреса точки назначения, которая является адресом узла (как определено маской подсети).
- Параметр
-p
поддерживается в команде route только в операционных системах Windows NT 4.0, Windows 2000, Windows Millennium Edition и Windows XP. Этот параметр не поддерживается командой route в системах Windows 95 и Windows 98. - Эта команда доступна, только если в свойствах сетевого адаптера в объекте Сетевые подключения в качестве компонента установлен протокол Интернета (TCP/IP).
Примеры
Чтобы вывести на экран все содержимое таблицы IP-маршрутизации, введите команду:
route print
Чтобы вывести на экран маршруты из таблицы IP-маршрутизации, которые начинаются с 10., введите команду:
route print 10.*
Чтобы добавить маршрут по умолчанию с адресом стандартного шлюза 192.168.12.1, введите команду:
route add 0.0.0.0 mask 0.0.0.0 192.168.12.1
Чтобы добавить маршрут к конечной точке 10.41.0.0 с маской подсети 255.255.0.0 и следующим адресом перехода 10.27.0.1, введите команду:
route add 10.41.0.0 mask 255.255.0.0 10.27.0.1
Чтобы добавить постоянный маршрут к конечной точке 10.41.0.0 с маской подсети 255.255.0.0 и следующим адресом перехода 10.27.0.1, введите команду:
route -p add 10.41.0.0 mask 255.255.0.0 10.27.0.1
Чтобы добавить маршрут к конечной точке 10.41.0.0 с маской подсети 255.255.0.0 и следующим адресом перехода 10.27.0.1 и метрикой стоимости 7, введите команду:
route add 10.41.0.0 mask 255.255.0.0 10.27.0.1 metric 7
Чтобы добавить маршрут к конечной точке 10.41.0.0 с маской подсети 255.255.0.0 и следующим адресом перехода 10.27.0.1 и использованием индекса интерфейса 0х3, введите команду:
route add 10.41.0.0 mask 255.255.0.0 10.27.0.1 if 0x3
Чтобы удалить маршрут к конечной точке 10.41.0.0 с маской подсети 255.255.0.0, введите команду:
route delete 10.41.0.0 mask 255.255.0.0
Чтобы удалить все маршруты из таблицы IP-маршрутизации, которые начинаются с 10., введите команду:
route delete 10.*
Чтобы изменить следующий адрес перехода для маршрута с конечной точкой 10.41.0.0 и маской подсети 255.255.0.0 с 10.27.0.1 на 10.27.0.25, введите команду:
route change 10.41.0.0 mask 255.255.0.0 10.27.0.25
Справочная информация
In Windows environments, a routing table defines paths for network traffic by mapping destination networks to specific interfaces and gateways. It contains entries that dictate how outbound data packets traverse various subnets and reach their destinations. Analyzing this information helps identify misconfigurations, improve connectivity, and ensure stable communication across diverse network segments.
Observing the routing table supports conflict resolution, route optimization, and adherence to intended policies. Tools like the route command provide real-time visibility into static and dynamic entries, revealing how the operating system decides where to forward traffic under different conditions.
Accurate routing details enable administrators and power users to troubleshoot connectivity issues, confirm proper configurations, and detect anomalies. Inspecting these routes makes it possible to validate system behavior, maintain efficient data flow, and uphold secure networking practices.
Using the Command Prompt:
-
Launch the Command Prompt from the Start menu.
-
Display all current routes.
C:\> route print =========================================================================== Interface List 9...00 1F 3C 6C 0B 42 ...... Intel(R) Ethernet Connection 10...00 15 5D 43 3B 02 ...... Hyper-V Virtual Ethernet Adapter =========================================================================== IPv4 Route Table =========================================================================== Active Routes: Network Destination Netmask Gateway Interface Metric 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.100 10 ...
-
Inspect the Active Routes section to identify paths, gateways, and metrics.
-
Filter the output by specifying a destination.
route print 192.168.0.0
Use route with caution when adjusting or deleting entries to avoid unintended loss of connectivity.
-
Close the Command Prompt when finished.
Using Windows PowerShell:
This method uses the Get-NetRoute cmdlet to display and manage routes using more modern administrative tools.
-
Right-click on the Start button and select Windows PowerShell (Admin).
-
List all routes in the current configuration.
PS C:\> Get-NetRoute ifIndex DestinationPrefix NextHop RouteMetric ... ------ ----------------- ------- ----------- ... 10 0.0.0.0/0 192.168.1.1 10 ... 10 192.168.1.0/24 0.0.0.0 10 ...
-
Filter routes by prefix.
Get-NetRoute -DestinationPrefix 192.168.1.0/24
PowerShell provides detailed information such as interface indexes and route metrics, which can be useful for advanced troubleshooting.
-
Exit PowerShell after reviewing the results.
Discuss the article:
Comment
anonymously. Login not required.