Sometimes you need to create static route entries to make communication with different networks that are connected via a different gateway. A gateway is simply a network router that routes the network traffic between different networks. When you have more than one gateway (router) on your network, then you may need to implement static route technique on Windows 10/Windows 11 or Windows servers/any Operating system.
A static route will tell the Operating System to send network packets to the appropriate router instead of sending them to the default router. This simple guide shows how to add, delete and modify a static route to the routing table on Windows 11/10 and Microsoft Server Operating Systems.
There are a few useful commands you must know. Route delete, add and print. These commands will be handy to any user who has administrative access and know which router/gateway should be used for which network.
Why Add Static Route?
It mostly depends on the network setup. Usually, you can add these static routes on your default router (if it can support) or core switch. When you have this kind of proper network setup, you do not need to add a static route to each computer separately on the network. But in a few exceptional cases, you may need to implement static routes on individual computers. Here are a few examples.
- You have more than one internet router on the network and you need to send traffic to certain websites (based on their IP addresses) via a different router than the default gateway. Let’s say, for example, all traffic to Netflix can be sent via the 2nd internet router where other website traffic can go through the 1st internet router.
- There are several VLANs or subnets available on the network. Before building the proper routing table on the router or core switch, adding a static route on your Windows computer will help you to test the connectivity see the traffic flow.
- For network security or isolation purpose, certain routes can’t be added to the default gateway device. In this case, as a network administrator, you can add the static route on a local computer to make network communication.
Route Add on Windows 11/10 and Windows Servers
Though there are major changes and interface upgrades in the latest Windows 11, the below steps remain the same.
Make sure you run the below commands on command prompt (or PowerShell) which is opened as Administrator.
Here is the command to add a static route to the routing table.
route ADD destination_network MASK subnet_mask gateway_ip metric_cost
route add 10.10.10.0 mask 255.255.255.0 10.10.29.1
It indicates that any packets to 10.10.10.0 (in class C – 255.255.255.0) network should be forwarded to the 10.10.29.1 router (gateway).
Obviously, the PC/server in which we run this command is in the 10.10.29.0/24 network because it should communicate to the gateway from the same network.
The issue with the above command is when you shut down or restart the computer, these route entries will be removed. To make it permanent and add to the Windows OS routing table, we should use the –p key with the add command. So, adding a persistent (or permanent) static route on Windows 10 command will be like this;
route add –p 10.10.10.0 mask 255.255.255.0 10.10.29.1
Route Print
Route print command is another useful command to view the entries on the routing table and which routes are active at the moment. If you need to modify an entry that is already in the routing table, better to confirm the entries before changing. To do it, use the route print command.
Route print
Also, we can view the persistent routes in a Windows OS by checking the following registry path. Look for the entries in this area before or after modifying any routing table entries.
HKEY_LOCAL_MACHINE->SYSTEM->CurrentControlSet-> Services->Tcpip->Parameters->PersistentRoutes
Route Delete on Windows 11/10 & Windows 2022/2019/2016 Servers
The below command is to delete an existing persistent route from a computer. Even though we added a route entry with the network, network mask and gateway, but to delete, we need to mention the network only. So, it goes like this;
route delete 10.10.10.0
That will delete the 10.10.10.0 route entry from the computer. You do not need to restart the computer to take effect. Adding and deleteting route entries take effect instantly.
Let’s say that after the recent network change, now the network 10.10.10.0 should be routed through the 10.10.29.200 gateway. Obviously, you have to modify the existing route for this network and change the gateway to 10.10.29.200.
So, how to modify the existing route entry? You can’t modify an existing entry.
The simple method is to delete it and add the new entry. So, in this case, you would perform the below commands.
Route delete 10.10.10.0 Route add –p 10.10.10.0 mask 255.255.255.0 10.10.29.200
We hope this simple guide is helpful in understanding the route add, delete and print commands in Windows 10/Windows 11 client PC and other server Operating Systems. Make sure you open the command prompt or PowerShell as Administrator to perform these commands. If you want to use cosmetic variables to identify the fast hops to reach a network, you can use the metric key as described at the Microsoft site here.
Ответ на частые вопросы:
- Как добавить статический маршут ?
- Как посмотреть таблицу маршрутизации ?
Для примера будем добавлять маршрут в сеть 10.10.0.0/16 (маска 255.255.0.0) через gateway 10.10.1.1/24
Не забывайте, что маршрут добавится ТОЛЬКО если на вашем компьютере есть IP-адрес который входит в одну подсеть с gateway (в данном примере gateway 10.10.1.1, значит у вас должен быть настроен IP-адрес из сети 10.10.1.0/24 т.к IP-адрес gateway имеет маску /24 (255.255.255.0))
FreeBSD
Добавление:
route add 10.10.0.0/16 10.10.1.1
если после выполнения команды вам говорится, что команда не найдена, то используйте полный путь до команды route (и для других команд):
/sbin/route
так же если прочитать:
man route
то можно узнать, что статический роутинг можно добавить и так:
/sbin/route add -net 10.10.0.0 -netmask 255.255.0.0 10.10.1.1
Просмотр таблицы маршрутизации выполняется командой:
netstat -rn
с полным путем:
/usr/bin/netstat -rn
Удаление:
/sbin/route delete 10.10.0.0/16
Linux
Добавление:
route add -net 10.10.0.0/16 gw 10.10.1.1
альтернатива:
ip route add 10.10.0.0/16 via 10.10.1.1
Просмотр таблицы:
route -n
или используйте:
ip route
Удаление:
route delete -net 10.10.0.0 netmask 255.255.0.0
Windows
Откройте командную строку (cmd).
Добавление:
route add 10.10.0.0 mask 255.255.0.0 10.10.1.1
Просмотр:
route print
Удаление:
route delete 10.10.0.0 mask 255.255.0.0 10.10.1.1
Если у Вас все ещё есть вопросы, то прочтите мануал (инструкцию) к данным командам в Вашей ОС.
З.Ы. При копировании статьи ссылка на источник ОБЯЗАТЕЛЬНА !
Автор: Николаев Дмитрий (virus (at) subnets.ru)
Похожие статьи:
- Не найдено
Прочитано: 248 842 раз(а)
Загрузка…
Отправить на почту
Эта статья размещена virus 23.09.2008 в 11:19 в рубриках Networks. Метки: FreeBSD, Linux, routing, Windows.
Вы можете оставить отзыв или trackback с вашего собственного сайта. Отслеживайте все отзывы и комментарии к этой статье при помощи новостной ленты RSS.
Есть два ПК: один в сети 192.168.1.0/24, другой в сети 192.168.2.0/24. Они не пингуют друг друга. Связаны сети через роутер с двумя IP: 192.168.1.253 и 192.168.2.254.
На компе с адресом 192.168.1.150 есть дополнительный маршрут по умолчанию с On-Link в качестве шлюза (метрика 20). Дополнительный потому что есть второй маршрут, где шлюзом указан роутер 192.168.1.253 (метрика 21).
Если маршрут с On-Link удалить, то компы пингуются. Но после перезагрузки он добавляется обратно. Как сделать так, чтобы этот маршрут не создавался автоматически? Или, может, его метрику увеличить, чтобы сначала выбирался другой маршрут по умолчанию. Только не вручную, а групповой политикой для всех компов в сети.
Справа как должно быть:
-
Вопрос задан
-
712 просмотров
Содержание
Маршруты — это сетевые установки, которые используются операционной системой для организации трифака и доступа к локальной сети и в Интернет. С помощью этой странички вы научитесь просматривать, удалять и добавлять маршруты на компьютере с ОС Windows от XP до 10. Все эти действия выполняются в командной строке или ее улучшенном и расширенном аналоге PowerShell.
Хочется также сказать о том, что если вы не уверены в своих знаниях, лучше не изменять данные настройки. Т.к. при неправильном использовании маршрутизации вы можете оставить ваш компьюетр без доступа к сети Интернет.
Просмотр маршрутов
Наберите команду
route print
Удаление всех статических маршрутов:
route -f
Добавление статического маршрута:
route -p add 0.0.0.0 mask 0.0.0.0 192.168.95.1
Удаляем все маршруты: route -f
После того, как все маршруты стёрты, естественно пропадёт Интернет. Для того, чтобы он появился вновь, необходимо задать маршрут по умолчанию. Добавляем постоянный маршрут к шлюзу:
route -p add 0.0.0.0 0.0.0.0 192.168.10.254 OK
В Windows XP/2003 Server после этого появится Интернет. Но если у вас Windows 7/8.1/или 2008/2012 Server, необходимо также выполнить команды:
ipconfig /release
ipconfig /renew
Как удалённо очистить таблицу маршрутов
Если вы хотите проделать все эти операции удалённо, вам понадобится программа NetAdapter Repair (подробнее). Дело в том, что после применения команды route -f соединение с сервером будет утрачено. А утилита NetAdapter Repair автоматически перезагрузит компьютер после очистки таблицы маршрутов. Для удалённой очистки необходимо проделать следующие действия:
1 Запустить утилиту NetAdapter Repair от имени Администратора.
2 Установить флажок возле пункта Clear ARP/Route Table.
3 Нажать кнопку Run All Selected:
После выполнения операции пойдёт обратный отсчёт времени и компьютер (сервер) перезагрузится автоматически:
Если что-то непонятно, спрашивайте в комментариях.
Static routes define fixed paths for network traffic that would otherwise have their path calculated automatically. This guide explains static routes, why you would use them, and provides step-by-step instructions showing how to add and remove static routes on Windows. It also looks at adding persistent routes and other tips for network management on Windows.
Get full control over your Windows networks with NinjaOne’s powerful endpoint management tools.
Try it for free.
What are static routes?
In computer networking, a “route” is the path network packets take to reach their destination. Data from your computer is broken into small packets for transfer over the local network (for example, between your computer and wireless printer), or for transmission over the internet (such as when you submit an online form). Network routing then takes care of making sure all of these packets reach their destination where they can be re-assembled into the original complete message.
Computer networks are designed in this way so that if there’s a disruption somewhere in the network, packets can be re-routed through a different connection. When there is no disruption, routing protocols can optimize for efficiency, sending data through different paths simultaneously to improve speed.
The key components in network routing are:
- Routing table: This is where each device (including your Windows PC) stores the information about the routes to different destinations.
- Next hop: Most network routes need to cover large distances over complex networks. The “next hop” is the next stop along the path to the destination (for example, there is a hop between your PC and a wireless printer — packets need to go first to your Wi-Fi router, then your printer).
- Routing protocols and metrics: Routing protocols are the software that is used by network devices to keep routing tables up-to-date with the latest paths data should take. This is done based on the number of hops, bandwidth, and/or latency.
Usually, routes are automatically calculated by the routing protocol and stored in a routing table based on routing metrics. These dynamic routes change based on network conditions. The default route can be set for all traffic with no route otherwise assigned in the routing table.
Static routes can be manually configured in a devices routing table, to set fixed paths traffic should take instead of dynamic routes or the default route. If this route is broken, traffic will not be able to reach the destination and a dynamic alternate route will not be calculated.
Why do you need to use static routes?
In some situations, the dynamic route is not the route you want specific traffic to take. You may want to take a known optimal route or send traffic along a secure connection. Example use-cases for static routes include:
- Sending traffic via a known reliable route that avoids faulty networking conditions that are outside your control or that fully utilizes a better connection for optimization.
- Building efficient networks using low-power devices that do not need to run routing protocols.
- Maintaining full control over the path network traffic takes for optimization or to ensure protected data only travels over your secure network infrastructure.
- Ensuring network traffic takes a predictable path for troubleshooting or easier management.
- Adding redundancy and resiliency to your networks by providing a known alternative path as a fallback to dynamic routes.
Static routes are frequently used to ensure certain traffic is sent over a VPN connection. This can be important when you handle sensitive data that you do not want routed over the internet. While static routes are usually not required for day-to-day tasks on home Windows PCs, there are situations where they are added for troubleshooting or to set up remote networks for work-from-home setups.
IP addresses and network masks
Route tables use the IPV4 or IPV6 IP address of the destination and hops to identify routes. You’ll need a basic understanding of IP addresses and network masks to write effective static routes.
How to use the route command for Windows
The route command is built-in to Windows and lets you view currently set static routes, as well as adding, removing, and editing them. The route command is available in all versions of Windows including Windows 11, Windows 10, and Windows Server. The route command can be run from either the Command Prompt or PowerShell, and needs to be run as an administrator.
To open PowerShell or the Command Prompt to use the route command, right-click on the Start menu, and then:
- Click Terminal (Admin) if you’re using Windows 11
- Click Command Prompt (Admin) if you’re using Windows 10
How to list static routes on Windows
To list the existing static routes, enter the following command:
route print
This will output the current route table, showing all the currently configured static routes. You can use this command to verify that you’ve successfully added, removed, or edited a static route.
How to add a static route on Windows
The below example route command adds a static route:
route add 0.0.0.0 mask 0.0.0.0 192.168.77.1
The command is constructed as follows:
- The route executable is called.
- The add command tells it to add a static route to the routing table.
- The first 0.0.0.0 is the destination network. In this case, 0.0.0.0 matches all networks.
- The second 0.0.0.0 specifies the subnet mask this static route should apply to, in this case again matching all subnets.
- 192.168.77.1 specifies the gateway address. This is the next hop through which all matching traffic will be sent.
This static route sends all network traffic to 192.168.77.1, effectively adding a default route.
The next example adds a route to a specific network:
route add 192.168.10.0 mask 255.255.255.0 192.168.77.1
The command differs from the previous example:
- 192.168.10.0 is the destination network.
- 255.255.255.0 specifies the subnet mask this static route should apply to, in this case matching all addresses in the 192.168.10.0 subnet.
- 192.168.77.1 specifies the gateway address. This is the next hop through which all matching traffic will be sent.
In effect, this static route sends traffic destined for the 192.168.10.0 network to 192.168.77.1.
How to remove a static route on Windows
To delete a static route, use the route delete command, and match the details with the static route you wish to delete.
route delete 0.0.0.0 mask 0.0.0.0 192.168.77.1
The above command deletes the static route created in the previous step.
How to remove all static routes on Windows
To delete all static routes on Windows, use the command:
route -f
Make a static route permanent/persistent on Windows
Static routes will be cleared from the route table on Windows when you reboot. To make a persistent route — one that is permanent and will survive a reboot — add the -p parameter to your route add command:
route -p add 0.0.0.0 mask 0.0.0.0 192.168.77.1
Troubleshooting and best practices for managing static routes
If you are manually managing static routes on Windows machines, you should document which routes are set on which machines to avoid a forgotten static route, causing a troubleshooting issue.
You should also regularly review which static routes are set (this can be done using the route print command in Windows), and remove ones that are no longer required. Network monitoring solutions will assist with identifying network changes and broken routes that may need to be addressed.
If you are working in an enterprise environment with multiple devices that all require the same static routes, you should implement them at the network level rather than per device.
Windows route management tools
In addition to the route command that is built into Windows, you can use the following tools to manage routes and perform other networking tasks on Windows:
- NetRouteView is a free routing utility for Windows that provides a graphical interface for viewing, adding, and modifying static routes.
- Angry IP Scanner and Advanced IP Scanner can help you find and identify devices on your local network, and manage static routes on connected Windows devices by executing remote commands or scripts.
Effortlessly manage your Windows networks with NinjaOne’s time-saving automations and comprehensive control over devices.
➤ Find out more.
Managing large Windows networks efficiently
If you need to manage static routes on a fleet of Windows devices, either on a single network or in bring-your-own-device (BYOD) scenarios with traveling or remote employees, you shouldn’t rely on manually adding static routes and other network configurations to individual devices.
The NinjaOne remote management and monitoring platform (RMM) helps you secure, manage, and monitor Windows devices at scale, ensuring that they are all correctly configured. This allows you to deploy updated networking and security policies from a centralized interface, removing the time-consuming tasks of updating, cataloging, and enforcing static routes and other policies.