let's show how to use route add command under windows xp or 2003 to add a gateway on vpn connections.
firstly , supposing the default gateway on vpn connection is unchecked. ( i prefer this way )
and then rasdial to connect the vpn.
and then
route print -4
to show the table, as below:
C:\Users\Administrator>route print -4
===========================================================================
Interface List
19...........................clochase
12...e8 9a 8f c9 22 17 ......Qualcomm Atheros AR8151 PCI-E Gigabit Ethernet Con
troller (NDIS 6.20)
11...78 92 9c 57 c2 92 ......Intel(R) Centrino(R) Wireless-N 100
16...08 00 27 00 24 bc ......VirtualBox Host-Only Ethernet Adapter
1...........................Software Loopback Interface 1
13...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
14...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
18...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3
===========================================================================clearly the number before the vpn connection name is the interface id, which is used to add on-link route
let's issue a command like below
route add 192.168.3.0 mask 255.255.255.0 0.0.0.0 IF 19
ok! it's done. let's print again.
C:\Users\Administrator>route add 192.168.3.0 mask 255.255.255.0 0.0.0.0 if 19
OK!
C:\Users\Administrator>route print -4
===========================================================================
Interface List
19...........................clochase
12...e8 9a 8f c9 22 17 ......Qualcomm Atheros AR8151 PCI-E Gigabit Ethernet Con
troller (NDIS 6.20)
11...78 92 9c 57 c2 92 ......Intel(R) Centrino(R) Wireless-N 100
16...08 00 27 00 24 bc ......VirtualBox Host-Only Ethernet Adapter
1...........................Software Loopback Interface 1
13...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter
14...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #2
18...00 00 00 00 00 00 00 e0 Microsoft ISATAP Adapter #3
===========================================================================
IPv4 Route Table
===========================================================================
Active Routes:
Network Destination Netmask Gateway Interface Metric
0.0.0.0 0.0.0.0 192.168.1.2 192.168.1.105 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.105 281
192.168.1.105 255.255.255.255 On-link 192.168.1.105 281
192.168.1.255 255.255.255.255 On-link 192.168.1.105 281
192.168.2.0 255.255.255.0 192.168.3.254 192.168.2.254 26
192.168.2.254 255.255.255.255 On-link 192.168.2.254 281
192.168.3.0 255.255.255.0 On-link 192.168.2.254 26
192.168.3.255 255.255.255.255 On-link 192.168.2.254 281
192.168.56.0 255.255.255.0 On-link 192.168.56.1 276
192.168.56.1 255.255.255.255 On-link 192.168.56.1 276
192.168.56.255 255.255.255.255 On-link 192.168.56.1 276
222.247.55.130 255.255.255.255 192.168.1.2 192.168.1.105 26
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.56.1 276
224.0.0.0 240.0.0.0 On-link 192.168.1.105 281
224.0.0.0 240.0.0.0 On-link 192.168.2.254 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.56.1 276
255.255.255.255 255.255.255.255 On-link 192.168.1.105 281
255.255.255.255 255.255.255.255 On-link 192.168.2.254 281
===========================================================================
Persistent Routes:
None
标准
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.
Networking / Beginners
Using the route command displays or modifies the computer’s routing
table. For a typical computer that has a single network interface and is
connected to a local area network (LAN) that has a router, the routing table
is pretty simple and isn’t often the source of network problems. Still, if
you’re having trouble accessing other computers or other networks, you can
use the route command to make sure that a bad entry in the computer’s
routing table isn’t the culprit.
For a computer with more than one interface and that’s configured to work
as a router, the routing table is often a major source of trouble. Setting up
the routing table properly is a key part of configuring a router to work.
Displaying the routing table
To display the routing table (both IPv4 and IPv6) in Windows, use the route
print command. In Unix/Linux, you can just use route without any command
line switches. The output displayed by the Windows and Unix/Linux commands
are similar. Here’s an example from a typical Windows client computer:
C:\>route print ================================================================== Interface List 8 ...00 12 3f a7 17 ba ...... Intel(R) PRO/100 VE Network Connection 1 ........................... Software Loopback Interface 1 9 ...02 00 54 55 4e 01 ...... Teredo Tunneling Pseudo-Interface 10 ...00 00 00 00 00 00 00 e0 isatap.{D0F85930-01E2-402F-B0FC- 31DFF887F06F} ================================================================== IPv4 Route Table ================================================================== Active Routes: Network Netmask Gateway Interface Metric Destination 0.0.0.0 0.0.0.0 192.168.1.1 192.168.1.110 276 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.110 276 192.168.1.110 255.255.255.255 On-link 192.168.1.110 276 192.168.1.255 255.255.255.255 On-link 192.168.1.110 276 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.110 276 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.110 276 ================================================================= Persistent Routes: Network Address Netmask Gateway Address Metric 0.0.0.0 0.0.0.0 192.168.1.1 Default ================================================================= IPv6 Route Table ================================================================= Active Routes: If Metric Network Destination Gateway 9 18 ::/0 On-link 1 306 ::1/128 On-link 9 18 2001::/32 On-link 9 266 2001:0:4136:e38c:2c6c:670:3f57:fe91/128 On-link 8 276 fe80::/64 On-link 9 266 fe80::/64 On-link 10 281 fe80::5efe:192.168.1.110/128 On-link 8 276 fe80::cca:9067:9427:a911/128 On-link 9 266 fe80::2c6c:670:3f57:fe91/128 On-link 1 306 ff00::/8 On-link 9 266 ff00::/8 On-link 8 276 ff00::/8 On-link ================================================================= Persistent Routes: None C:\>
For each entry in the routing table, five items of information are listed:
- The destination IP address
Actually, this is the address of the destination subnet, and must be
interpreted in the context of the subnet mask. - The subnet mask that must be applied to the destination address to determine the destination subnet
- The IP address of the gateway to which traffic intended for the destination subnet will be sent
- The IP address of the interface through which the traffic will be sent to the destination subnet
- The metric, which indicates the number of hops required to reach destinations via the gateway
Each packet that’s processed by the computer is evaluated against the
rules in the routing table. If the packet’s destination address matches the
destination subnet for the rule, the packet is sent to the specified gateway
via the specified network interface. If not, the next rule is applied.
The computer on which I ran the route command in this example
is on a private 192.168.1.0 subnet. The computer’s IP address is
192.168.1.100, and the default gateway is a router at 192.168.1.1.
Here’s how the rules shown in this example are used. Notice that you have
to read the entries from the bottom up:
- The first rule is for packets sent to 255.255.255.255, with subnet
mask 255.255.255.255. This special IP address is for broadcast
packets. The rule specifies that these broadcast packets should be
delivered to the local network interface (192.168.1.100). - The next rule is for packets sent to 192.168.1.255, again with subnet
mask 255.255.255.255. These are also broadcast packets and are sent to the local network interface. - The next rule is for packets sent to 192.168.1.100, again with subnet
mask 255.255.255.255. This is for packets that the computer is
sending to itself via its own IP address. This rule specifies that these
packets will be sent to the local loopback interface on 127.0.0.1. - The next rule is for packets sent to 192.168.1.0, with subnet mask
255.255.255.0. These are packets intended for the local subnet.
They’re sent to the subnet via the local interface at 192.169.1.100. - The next rule is for packets sent to the loopback address (127.0.0.1,
subnet mask 255.0.0.0). These packets are sent straight through to
the loopback interface, 127.0.0.1. - The last rule is for everything else. All IP addresses will match the
destination IP address 0.0.0.0 with subnet mask 0.0.0.0 and will be
sent to the default gateway router at 192.168.1.1 via the computer’s
network interface at 192.168.1.100.
Tip: One major difference between the Windows version of route and the Unix/
Linux version is the order in which they list the routing table. The Windows
route command lists the table starting with the most general entry and
works toward the most specific. The Unix/Linux version is the other way
around: It starts with the most specific and works toward the more general.
The Unix/Linux order makes more sense — the Windows route command displays the routing list upside down.
Modifying the routing table
Besides displaying the routing table, the route command also lets you
modify it by adding, deleting, or changing entries.
Warning You shouldn’t do this unless you know what you’re doing. If you mess up the
routing table, your computer may not be able to communicate with anyone.
The syntax for the route command for adding, deleting, or changing a route entry is
route [-p] command dest [mask subnet] gateway [-if interface]
The following list describes each of the route command’s parameters:
- -p: Makes the entry persistent. If you omit -p, the entry will be deleted
the next time you reboot. (Use this only with add commands.) - command: Add, delete, or change.
- dest: The IP address of the destination subnet.
- mask subnet: The subnet mask. If you omit the subnet mask, the
default is 255.255.255.255, meaning that the entry will apply only to
a single host rather than a subnet. You usually want to include the mask. - gateway: The IP address of the gateway to which packets will be sent.
- -if interface: The IP address of the interface through which packets
will be sent. If your computer has only one network interface, you can omit this.
Suppose that your network has a second router that serves as a link to
another private subnet, 192.168.2.0 (subnet mask 255.255.255.0). The
interface on the local side of this router is at 192.168.1.200. To add a
static route entry that sends packets intended for the 192.168.2.0 subnet
to this router, use a command like this:
C:\>route -p add 192.168.2.0 mask 255.255.255.0 192.168.1.200
Now, suppose that you later change the IP address of the router to
192.168.1.222. You can update this route with the following command:
C:\>route change 192.168.2.0 mask 255.255.255.0 192.168.1.222
If you omit the mask from a route change command, the command changes the mask to 255.255.255.255!
Finally, suppose that you realize that setting up a second router on this
network wasn’t such a good idea after all, so you want to just delete the
entry. The following command will do the trick:
C:\>route delete 192.168.2.0
Статья про таблицу маршрутизации — тема, обещанная около четырех лет тому назад. На самом деле, давно нужно было про нее написать, но никак не мог решиться и только сейчас делаю попытку.
Манипуляции с таблицей маршрутизации позволяют тонко настраивать работу ваших сетей.
Чаще всего это не нужно, но иногда требуется сделать что-то необычное, особенно, когда на комрьютере несколько адаптеров, и тогда
приходится браться за таблицы маршрутизации.
Просмотр таблицы маршрутизации
Приведу вывод команды route print на моем стаионарном компьютере:
Сетевой адрес | Маска сети | Адрес шлюза | Интерфейс | Метрика |
---|---|---|---|---|
0.0.0.0 | 0.0.0.0 | 192.168.1.1 | 192.168.1.100 | 20 |
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.100 | 276 |
192.168.1.100 | 255.255.255.255 | On-link | 192.168.1.100 | 276 |
192.168.1.255 | 255.255.255.255 | On-link | 192.168.1.100 | 276 |
244.0.0.0 | 240.0.0.0 | On-link | 127.0.0.1 | 306 |
244.0.0.0 | 240.0.0.0 | On-link | 192.168.1.100 | 276 |
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.100 | 276 |
Вот так мы можем просмотреть таблицы маршрутизации. Попробуем описать, что все это означает. Каждая строчка опреедляет, куда отправлять какие пакеты.
То есть для диапазона, задаваемого значениями в колонках «сетевой адрес» и «маска сети» создается сетевой маршрут.
Например, адрес 192.168.0.1 и маска 255.255.255.0 означают, что имеется в виду диапазон 192.168.0.*.
Маска всегда имеет вид, когда вначале стоят 255, в конце — нули, а последним ненулевым числом может быть степень двойки минус один.
Например, для маски 255.255.127.0 и того же адреса 192.168.0.1 диапазон будет чуть шире, в него войдут и адреса
вида 192.168.1.*. Чтобы описать это точнее, надо представить все числа в двоичном виде, но это не является целью статьи.
Итак, если мы определились с диапазоном, мы должны понять, куда же компьютер будет направлять пакеты, если они предназначены
адресам из этого диапазона. Начнем с четвертой колонки. Она определяет тот адаптор, на который нужно отправлять пакеты.
Например, в данном случае, в ней встречаются 192.168.1.100 — это адрес моей сетевой карты и 127.0.0.1 —
так называемая обратная петля. Пакеты «на этот адаптор» компьютер даже не будет пытаться отправлять куда-либо.
Если бы у меня была активна другая карта, например, WiFi, то в четвертой колонке встречался бы и е адрес.
Третья колонка определяет «шлюз» — тот маршрутизатор, которому нужно послать эти пакеты. В случае, когда там написано «On-link»,
имеется в виду, что никаких маршрутизаторов не нужно — адрес и так находится в прямой досягаемости. Последняя колонка — метрика.
Она определяет предпочтение для маршрута, когда есть варианты. Строчки с наименьшей метрикой предпочтительны при
совпадении диапазонов.
Итак, давайте разберем описанные маршруты. На самом деле, самой важной является в данном случае первая строчка.
Она говорит, что для любого адреса (адрес 0.0.0.0 с маской 0.0.0.0 задает полный диапазон) есть маршрут
с использованием моей сетевой карты, и направить можно эти пакеты по адресу 192.168.1.1. Последний адрес
является моим роутером, что все и объясняет. Любой адрес, который компьютер не сможет
найти где-то рядом, он направит на роутер и предоставит тому с ним разбираться.
Поговорим про остальное. Три строчки про 127 — системные, связаны с тем, что эти адреса всегда должны возвращаться
на сам компьютер. Адреса диапазона 192.168.1.* являются локальной сетью, 192.168.1.100 — вообще наш адрес,
192.168.1.255 — специальный адрес для широковещательных пакетов в локальной сети.
Адреса 244.0.0.0 — тоже специальные зафиксированные адреса для широкого вещания, а две последние строчки
определяют сами адаптеры.
Но этот случай достаточно неинтересный. Посмотрим на таблица на моем роутере.
Внешний вид будет немного другой, поскольку на нем Линукс, и я вывожу соответствующие таблицы командой route -n.
Destination | Gateway | Genmask | Flags | Metric | Ref | Use | Iface |
---|---|---|---|---|---|---|---|
10.0.20.43 | 0.0.0.0 | 255.255.255.255 | UH | 0 | 0 | 0 | ppp0 |
192.168.1.0 | 0.0.0.0 | 255.255.255.0 | U | 0 | 0 | 0 | br0 |
10.22.220.0 | 0.0.0.0 | 255.255.255.0 | U | 0 | 0 | 0 | vlan1 |
10.0.0.0 | 10.22.220.1 | 255.224.0.0 | UG | 0 | 0 | 0 | vlan1 |
127.0.0.0 | 0.0.0.0 | 255.0.0.0 | U | 0 | 0 | 0 | lo |
0.0.0.0 | 10.0.20.43 | 0.0.0.0 | UG | 0 | 0 | 0 | ppp0 |
Заметим сразу, что колонки немного изменились. На всех мы останавливаться не будем, существенной измененной колонкой является
последняя — вместо IP-адреса адаптора мы указываем его имя. Здесь lo — это «петля» (никуда не отправлять),
br0 — внутренняя сеть, ppp0 — внешняя, vlan0 — установленное vpn-содениение. Итак, разберем строчки.
Также в колонке с флагами буква G означает Gateway — шлюз, а H — Host, наш компьютер.
Последняя строчка — шлюз по умолчанию. Любой пакет мы может отправить на адрес 10.0.20.43.
Что интересно, это — наш собственный адрес, полученный при установке VPN — соединения!
Так всегда получается, когда установлено VPN-соединения, пакет, в первую очередь отправляем своему виртуальному интерфейсу,
где он инкапсулируется в другой пакет, который пойдет до реального шлюза. Естественно, в таблицах маршрутизации этого не видно.
Также к описанию этого соединения относится и первая строчка.
Настоящий шлюз мы видим в третей строчке — адресы диапазона 10.22.220.* отправляются на vlan1, шлюз,
предоставленный провайдером, коммуникатор, с которым мы соединены сетевым кабелем напрямую.
Вторая строчка говорит о том, что адреса диапазона 192.168.1.* — это локальная сеть, и пакеты
к ним нужно отправлять внутрь, а не вовне. Пятая — обычная информация про «локальные адреса».
Команды таблицы маршрутизации
Я ничего не сказал про предпоследнюю строчку. А она самая интересная, ведь я ее добавил руками.
В чем ее смысл? Адреса диапазона 10.1-32.*.* я отправляю на шлюз 10.22.220.1. Пакеты на эти адреса не пойдут
в интернет, а останутся в локалке провайдера. Да, пакеты на диапазон 10.22.220. и так идут туда,
но этого мало. Так я не получаю полноценного доступа к локальным ресурсам.
В случае Windows такой маршрут в таблицы маршрутизации был бы добавлен командой
route -p add 10.0.0.0 mask 255.224.0.0 10.22.220.1. -p означает, что маршрут постоянный,
он не должен удаляться после перезагрузки компьютера.
Статья и так уже получилась намного длинней обычных статей этого блога, так что я заканчиваю.
Пишите свои вопросы здесь, а если же вы хотите разобрать какие-то спицифические случаи настройки,
лучше обращайтесь на нашем форуме.
comments powered by