Arp в роутере что это

Протокол ARP и «с чем его едят» (дополнено)

Спасибо хабраюзеру hardex за публикацию первоначальной статьи, а также всем, кто плюсанул в карму для возможности моей собственноручной публикации. Теперь дополненная версия с учетом пожеланий и дополнений. Добро пожаловать под кат.

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

Как известно, адресация в сети Internet представляет собой 32-битовую последовательность 0 и 1, называющихся IP-адресами. Но непосредственно связь между двумя устройствами в сети осуществляется по адресам канального уровня (MAC-адресам).

Так вот, для определения соответствия между логическим адресом сетевого уровня (IP) и физическим адресом устройства (MAC) используется описанный в RFC 826 протокол ARP (Address Resolution Protocol, протокол разрешения адресов).

ARP состоит из двух частей. Первая – определяет физический адрес при посылке пакета, вторая – отвечает на запросы других станций.

Протокол имеет буферную память (ARP-таблицу), в которой хранятся пары адресов (IP-адрес, MAC-адрес) с целью уменьшения количества посылаемых запросов, следовательно, экономии трафика и ресурсов.

Пример ARP-таблицы.

192.168.1.1 08:10:29:00:2F:C3
192.168.1.2 08:30:39:00:2F:C4

Слева – IP-адреса, справа – MAC-адреса.

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

Записи ARP-таблицы бывают двух вид видов: статические и динамические. Статические добавляются самим пользователем, динамические же – создаются и удаляются автоматически. При этом в ARP-таблице всегда хранится широковещательный физический адрес FF:FF:FF:FF:FF:FF (в Linux и Windows).

Создать запись в ARP-таблице просто (через командную строку):

Вывести записи ARP-таблицы:

После добавления записи в таблицу ей присваивается таймер. При этом, если запись не используется первые 2 минуты, то удаляется, а если используется, то время ее жизни продлевается еще на 2 минуты, при этом максимально – 10 минут для Windows и Linux (FreeBSD – 20 минут, Cisco IOS – 4 часа), после чего производится новый широковещательный ARP-запрос.

Сообщения ARP не имеют фиксированного формата заголовка и при передаче по сети инкапсулируются в поле данных канального уровня

Формат сообщения ARP.

  • тип сети (16 бит): для Ethernet – 1;
  • тип протокола (16 бит): h0800 для IP;
  • длина аппаратного адреса (8 бит);
  • длина сетевого адреса (8 бит);
  • тип операции (16 бит): 1 – запрос, 2 — ответ;
  • аппаратный адрес отправителя (переменная длина);
  • сетевой адрес отправителя (переменная длина);
  • аппаратный адрес получателя (переменная длина);
  • сетевой адрес получателя (переменная длина).
Читайте также:  Роутеры от аиста настройка

А вот как происходит определение маршрута с участием протокола ARP.

Пусть отправитель A и получатель B имеют свои адреса с указанием маски подсети.

  1. Если адреса находятся в одной подсети, то вызывается протокол ARP и определяется физический адрес получателя, после чего IP-пакет инкапсулируется в кадр канального уровня и отправляется по указанному физическому адресу, соответствующему IP-адресу назначения.
  2. Если нет – начинается просмотр таблицы в поисках прямого маршрута.
  3. Если маршрут найден, то вызывается протокол ARP и определяется физический адрес соответствующего маршрутизатора, после чего пакет инкапсулируется в кадр канального уровня и отправляется по указанному физическому адресу.
  4. В противном случае, вызывается протокол ARP и определяется физический адрес маршрутизатора по умолчанию, после чего пакет инкапсулируется в кадр канального уровня и отправляется по указанному физическому адресу.

Главным достоинством проткола ARP является его простота, что порождает в себе и главный его недостаток – абсолютную незащищенность, так как протокол не проверяет подлинность пакетов, и, в результате, можно осуществить подмену записей в ARP-таблице (материал для отдельной статьи), вклинившись между отправителем и получателем.

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

Существуют еще протоколы InARP (Inverse ARP), который выполняет обратную функцую: по заданному физическому адресу ищется логический получателя, и RARP (Reverse ARP), который схож с InARP, только он ищет логический адрес отправителя.

В целом, протокол ARP универсален для любых сетей, но используется только в IP и широковещательных (Ethernet, WiFi, WiMax и т.д.) сетях, как наиболее широко распространенных, что делает его незаменимым при поиске соответствий между логическими и физическими адресами.

P.S. Эту статью писал я сам, никуда не подглядывая, основываясь только на своих знаниях, полученных в ходе изучения сетей.

Источник

Summary

Even though IP packets are addressed using IP addresses, hardware addresses must be used to actually transport data from one host to another. Address Resolution Protocol is used to map OSI level 3 IP addresses to OSI level 2 MAC addresses. A router has a table of currently used ARP entries. Normally the table is built dynamically, but to increase network security, it can be partially or completely built statically by means of adding static entries.

Properties

This section describes the ARP table configuration options.

Property Description
address (IP; Default: ) IP address to be mapped
interface (string; Default: ) Interface name the IP address is assigned to
mac-address (MAC; Default: 00:00:00:00:00:00) MAC address to be mapped to
published (yes | no; Default: no) Static proxy-arp entry for individual IP addresses. When an ARP query is received for the specific IP address, the device will respond with its own MAC address. No need to set proxy-arp on the interface itself for all the MAC addresses to be proxied. The interface will respond to an ARP request only when the device has an active route towards the destination
Читайте также:  Wifi роутер минимального размера

Read-only properties:

Property Description
dhcp (yes | no) Whether the ARP entry is added by DHCP server
dynamic (yes | no) Whether the entry is dynamically created
invalid (yes | no) Whether the entry is not valid

The default maximum number of ARP entries depends on the installed amount of RAM. It can be adjusted with the command «/ip settings set max-neighbor-entries=x», see more details on IPv4 Settings.

ARP Modes

It is possible to set several ARP modes on the interface configuration.

  • disabled — the interface will not use ARP
  • enabled — the interface will use ARP
  • local-proxy-arp — the router performs proxy ARP on the interface and sends replies to the same interface
  • proxy-arp — the router performs proxy ARP on the interface and sends replies to other interfaces
  • reply-only — the interface will only reply to requests originated from matching IP address/MAC address combinations which are entered as static entries in the IP/ARP table. No dynamic entries will be automatically stored in the IP/ARP table. Therefore for communications to be successful, a valid static entry must already exist.

Disabled

If the ARP feature is turned off on the interface, i.e., arp=disabled is used, ARP requests from clients are not answered by the router. Therefore, a static ARP entry should be added to the clients as well. For example, the router’s IP and MAC addresses should be added to the Windows workstations using the arp command:

C:\> arp -s 10.5.8.254 00-aa-00-62-c6-09

Enabled

This mode is enabled by default on all interfaces. ARPs will be discovered automatically and new dynamic entries will be added to the ARP table.

Proxy ARP

A router with a properly configured proxy ARP feature acts as a transparent ARP proxy between different networks.

This behavior can be useful, for example, if you want to assign dial-in (ppp, pppoe, pptp) clients’ IP addresses from the same address space as used on the connected LAN.

Proxy ARP can be enabled on each interface individually with command arp=proxy-arp:

[admin@MikroTik] /interface ethernet> set 1 arp=proxy-arp [admin@MikroTik] /interface ethernet> print Flags: X - disabled, R - running # NAME MTU MAC-ADDRESS ARP 0 R ether1 1500 00:30:4F:0B:7B:C1 enabled 1 R ether2 1500 00:30:4F:06:62:12 proxy-arp

Reply Only

If ARP property is set to reply-only on the interface, then the router only replies to ARP requests. Neighbour MAC addresses will be resolved only using statically configured entries from the «/ip arp» menu, but there will be no need to add the router’s MAC address to other hosts’ ARP tables like in case if ARP is disabled.

Читайте также:  Роутер tp link tl mr150 характеристики

Local Proxy Arp

If the ARP property is set to local-proxy-arp on an interface, then the router performs proxy ARP to/from this interface only. i.e. for traffic that comes in and goes out of the same interface. In a normal LAN, the default behavior is for two network hosts to communicate directly with each other, without involving the router.

With local-proxy-arp enabled, the router will respond to all client hosts with the router’s own interface MAC address instead of the other host’s MAC address.

E.g. If Host A (192.168.88.2/24) queries for the MAC address of Host B (192.168.88.3/24), the router would respond with its own MAC address. In other words, if local-proxy-arp is enabled, the router would assume responsibility for forwarding traffic between Host A 192.168.88.2 and Host B 192.168.88.3. All the ARP cache entries on Hosts A and B will reference the router’s MAC address. In this case, the router is performing local-proxy-arp for the entire subnet 192.168.88.0/24.

An example for RouterOS local-proxy-arp could be a bridge setup with a DHCP server and isolated bridge ports where hosts from the same subnet can reach each other only at Layer3 through bridge IP.

/interface bridge add arp=local-proxy-arp name=bridge1 /interface bridge port add bridge=bridge1 horizon=1 interface=ether2 add bridge=bridge1 horizon=1 interface=ether3 add bridge=bridge1 horizon=1 interface=ether4

Gratuitous ARP

It is possible to create Gratuitous ARP requests in RouterOS. To do so you must use the Traffic-Generator tool, below is an example of how to generate a Gratuitous ARP request to update the ARP table on a remote device:

/tool traffic-generator inject interface=ether2 \ data="ffffffffffff4c5e0c14ef78080600010800060400014c5e0c14ef780a057a01ffffffffffff0a057a01000000000000000000000000000000000000"

You must change the MAC address (4c5e0c14ef78) and the IP address (0a057a01) to your router’s address. The IP address and the MAC address must be from the device that requests an ARP table update. You also need to specify through which interface (ether2) you want to send the Gratuitous ARP request. Make sure that receiving device supports Gratuitous ARP requests.

Источник

Оцените статью
Adblock
detector