- Смена MTU
- Windows
- Командная строка
- Реестр
- Linux
- Разово
- Постоянно (permanently)
- Роутер
- Читайте также
- Setting mtu in windows
- Как сменить MTU через реестр
- Смена MTU на Windows через командную строку
- Зачем уменьшать MTU
- Уменьшаем MTU с помощью командной строки
- Определить минимальное значение MTU
- How to read, calculate and set MTU in Windows, Linux and OSX
- Theory – Identify ideal MTU
- MTU in Windows
- Read current MTU in Windows
- Determine the optimal MTU in Windows
- Set the MTU value in Windows
- MTU in OSX
- Read current MTU in OSX
- Determine the optimal MTU in OSX
- Set MTU value in OSX
- MTU in Linux
- Read current MTU in Linux
- Determine the optimal MTU in Linux
- Set the MTU value in Linux
Смена MTU
Рассмотрим процесс смены значения MTU для операционных систем семейства Windows и Linux, а также роутерах.
Windows
Командная строка
Открываем командную строку от имени администратора.
Вводим команду для просмотра текущего значения MTU и названия сетевого интерфейса:
netsh interface ipv4 show subinterfaces
Получаем, примерно, следующее:
MTU Состояние определения носителя Вх. байт Исх. байт Интерфейс
—— ————— ——— ——— ————-
1500 1 81324794839 5376993884 Ethernet
* где 1500 — значение MTU (по умолчанию для сетей Etnernet); Ethernet — название интерфейса.
Меняем MTU следующей командой:
netsh interface ipv4 set subinterface «Ethernet» mtu=1492 store=persistent
* где Ethernet — название сетевого интерфейса, которое мы получили предыдущей командой; 1492 — новое значение MTU
Реестр
Открываем реестр (команда regedit) и переходим по ветке HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\<4D36E972-E325-11CE-BFC1-08002bE10318.
Внутри будут находиться другие ветки с названиями 0000, 0001, 0002 и так далее. Необходимо пройтись по каждой и найти ключ DriverDesc со значением, похожим на название нашего сетевого адаптера и записать значение ключа NetCfgInstanceId, например:
Переходим в ветку HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces. Находим ветку с нашим идентификатором, который мы записали и меняем ключ MTU (при его отсутствии, создаем — тип DWORD):
Чтобы настройки применились выключаем и снова включаем сетевой интерфейс или перезагружаем компьютер.
Linux
Для примера, рассмотрим наиболее популярные дистрибутивы — CentOS и Ubuntu.
Разово
Разово (до перезагрузки) для данных двух систем настройку можно выполнить одной командой:
ip link set mtu 1400 dev eth0
* где 1400 — новое значение MTU; eth0 — сетевой интерфейс, для которого поменяли максимальный размер пакетов.
или в старых системах:
ifconfig eth0 mtu 1400
Постоянно (permanently)
Для систем на базе Debian (Ubuntu) и Red Hat (CentOS) процедура немного отличается.
Ubuntu
Открываем настройку сетевых интерфейсов:
К нужному адаптеру добавляем строчку:
iface eth0 inet static
.
mtu 9000
systemctl restart networking
CentOS
Открываем конфигурационный файл для соответствующего сетевого интерфейса:
Перезапускаем сетевую службу:
systemctl restart network
Роутер
Смена MTU на роутерах различных производителей выполняется, примерно, по одному и тому же принципу — зайти на веб-интерфейс для настройки маршрутизатора, найти раздел с настройкой сети Интернет, задать значение MTU.
Например, для большинства устройств TP-Link: Network — WAN:
Читайте также
Инструкция по смене значения MTU на Windows и Linux
Setting mtu in windows
Всем привет! Сегодня хочу рассказать как изменить MTU в Windows. Напомню MTU — Maximum transmission unit (MTU) — это максимальный объём данных, который может быть передан протоколом за одну итерацию. К примеру, Ethernet MTU равняется 1500, что означает, что максимальный объём данных, переносимый Ethernet фреймом не может превышать 1500 байт. Очень часто рядовым пользователям приходится его менять, когда необходимо раздать свой интернет
У каждого провайдера или сетевого устройства, данное значение может быть свое. например 1492 очень часто встречается на роутерах Dlink, и если устройству на устройство будет например приходить пакет 1500 байт, а у него мту настроено 1492, то часть пакетов будут приходить битые, глюки могут выражаться, например у вас не полностью будут отображаться интерфейс сайта, что то загрузилось, а что то нет, первый признак, проверить Maximum transmission unit.
Итак посмотрим какое значение mtu у гугла, откроем командную строку и вводим следующую команду.
Как изменить значение MTU в Windows 10, Windows 8.1, Windows 7-01
И смотрим ответ, если ответ получен без потери пакетов, то увеличиваем значение, если выдаст «Требуется фрагментация пакета, но установлен запрещающий флаг.», значит уменьшаем и так, пока не получим крайнее верхнее значение пакета, которое проходит до нашего сервера. У меня получилось 1500 (1472+28). Значит дальше я и буду его устанавливать в качестве значения MTU
Далее, вводим команду:
Она покажет MTU для всех сетевых подключений. Нам необходимо узнать как называется интерфейс основного сетевого подключения. Посмотреть названия можно командой
Как изменить значение MTU в Windows 10, Windows 8.1, Windows 7-04
либо в центре управления сетями.
Как изменить значение MTU в Windows 10, Windows 8.1, Windows 7-04
У меня это Ethernet, у вас же смотрите по обстановке. Но в большинстве случаев он будет называться так же.
Далее, вводим следующую команду (для ее выполнения требуется чтобы командная строка была запущена от имени администратора)
Где вместо Ethernet пишем название своего интерфейса, а в значение MTU пишем полученное на первом шаге инструкции
Как изменить значение MTU в Windows 10, Windows 8.1, Windows 7-06
как отключить автоматическую настройку значения MTU для сетевых подключений:
Чтобы включить автоматическую настройку обратно, нужно заменить disabled на normal
Как изменить значение MTU в Windows 10, Windows 8.1, Windows 7-07
После этого значение mtu будет такое как вам нужно. Вот мы с вами и разобрали как изменить mtu в Windows. Так что значение mtu теперь для вас не секрет.
Как сменить MTU через реестр
Для тех, кто не любит командную строку, есть PowerShell и реестр. В реестре Windows есть ветка:
Класс содержит информацию, о всех ваших сетевых картах, а именно драйверах, их версиях и GUID самой карты. GUID потребуется для определения сетевой карты в другой ветке реестра, но не переживайте я покажу более быстрый метод определения и сопоставления GUID и сетевой карты через PowerShell. На что в данном разделе нужно обратить внимание:
- Папки 0000, 0001 и так далее — это папки перечисляющие ваши сетевые интерфейсы в Windows, тут вам нужно будет найти нужный по параметрам указанными ниже
- DriverDesc — Описание драйвера, по сути вы увидите тут производителя вашей сетевой карты, оно поможет вам определить правильный адаптер
- NetCfgInstanceId — это GUID карточки
Теперь зная GUID идем по пути:
Среди интерфейсов находим нужный, можно удостовериться, что у него правильный IP-адрес. Найдите ключ MTU, если его нет, то нужно создать REG_DWORD с нужным значением.
Теперь как не заморачиваться с поиском GUID сетевой карты. Откройте PowerShell ISE и запустите мой скрипт:
$aGUID_SET = @(Get-ItemProperty «HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\*» | select -ExpandProperty pschildname)
Get-ItemProperty «HKLM:\SYSTEM\CurrentControlSet\Control\Class\<4d36e972-e325-11ce-bfc1-08002be10318>\*» -exclude «Properties» |
Where-Object <$aGUID_SET.Contains($_.NetCfgInstanceId)>|
ForEach-Object <
«»
$_.DriverDesc
$_.NetCfgInstanceId
>
Или просто если нужно вывести все GUID из нужной ветки:
Смена MTU на Windows через командную строку
Меняем MTU на сервере Windows с помощью командной строки. На тестовом сервере операционная система Windows Server 2016.
MTU (Maximum Transmission Unit) — максимальный размер полезного блока данных одного пакета. Если размер блока превышает MTU, то он может быть передан протоколом с использованием фрагментации.
Основные значения MTU в байтах:
- Ethernet — 1500
- 16 Mbps Token Ring — 17914
- 4 Mbps Token Ring — 4464
- FDDI — 4352
- IEEE 802.3/802.2 — 1492
- PPPoE (WAN Miniport) — 1480
- X.25 — 576
Зачем уменьшать MTU
Иногда бывает полезно уменьшить MTU на компьютере, чтобы ускорить скорость работы по сети. Классический случай, когда дома стоит роутер и на нём указан MTU 1480. Если на домашнем компьютере указано значение MTU 1500, то большие пакеты при передачи данных могут фрагментироваться. Тормозит потоковое видео или аудио, к примеру.
Уменьшаем MTU с помощью командной строки
Командная строка запущена под администратором.
Посмотреть текущее значение MTU:
У меня на интерфейсе Ethernet0 указано MTU 1500.
Установить значение MTU 1452 на интерфейсе Ethernet0:
Перезагружаем компьютер. Всё.
Сброс MTU на значение по умолчанию:
Определить минимальное значение MTU
Вычислить минимальное значение MTU между компьютером и узлом сети можно с помощью команды ping.
- -f — запрещает фрагментировать пакеты
- -l — размер пакета
Если пинг не проходит, то уменьшаем размер пакета.
У меня 1500 не проходит, а 1400 проходит. Истина где-то посередине. Методом научного пинга находим максимальный размер пакета, который проходит без фрагментации.
У меня получилось 1372. Прибавляем 28 байт (8 байт ICMP заголовок и 20 байт IP). 1372+28=1400.
How to read, calculate and set MTU in Windows, Linux and OSX
Before we look at the implementation within the individual operating systems, we first briefly clarify what the MTU is and how its optimal value can be calculated.
Theory – Identify ideal MTU
The MTU (Maximum Transfer Unit) describes the maximum packet size of a protocol. It therefore indicates the maximum size of a data packet, so that it can be transmitted via a protocol. If a data packet is larger, it becomes fragmented – i.e. divided into several packages.
For example, let’s assume that we (=PC) would have a factory for sugar packets and our packet size (=configured MTU) would be 1.5kg. Now the bakery has ordered 5 packages (5 x 1.5 kg) of sugar, but our postman (=network interface) can only transfer packets with a maximum size of 1kg (=protocol limit). What is he doing now? He fragments our sugar packets and divides them into 1kg and 0.5kg packs. So he needs two packages for transmission of one of our initial sugar packages. In addition, the postman has more work, because he has to mark which packages belong together. These multi-packets (=overhead) slow down the sending of packets (=data transfer speed).
[aawp box=”1119154723″ template=”list”]To solve the problem and speed up the shipping, we would have to dimension our packaging size (=MTU) so that the postman does not have to repackage (=fragment). The ideal MTU is 1kg in our case. In order to determine this value, we would have to ask the postal worker for the size limit, when he starts repackaging. The same story is true for computer systems.
In the IT, we send a data package by ping command and tell ping the size of the package as well as the info that this package should not be fragmented. If the packet size is too large, ping tells us that the package is not ok and that the package had to be fragmented, if it shall be send sucessfully.
Now we reduce the packet size until the error message of the fragmentation is omitted. This gives us the optimal package size. However, since the MTU also includes protocol information, we still have to add 28 bytes (20 bytes = IPv4 header and 8 bytes = ICMP) to the package size value to get the optimal MTU.
MTU in Windows
Read current MTU in Windows
To display the current MTU by console, use the following command, which must be entered into the CMD (Win + R key, “CMD”, “Ok” button):
This command generates a list that looks like this (or something similar):
The “MTU” column shows the MTU currently set for an interface. In addition, the “Idx” column is interesting since we need the Id from this column to set a new MTU value later.
Determine the optimal MTU in Windows
To determine the optimal MTU in Windows, we use the ping command in the console. By means of the “l” parameter, we set the packet size (this should be larger than the expected MTU for the time being) and use the “f” parameter to indicate that the package should not be fragmented.
Now we repeat the call and reduce the buffer size (in example 1550) with each call. If the ping could be executed and no longer show “packet needs to be fragmented but DF set” we are almost ready. To get the MTU size we add 28 bytes (header infos).
Set the MTU value in Windows
To set the MTU for a network interface, we need the desired MTU value as well as the ID of the network interface. The Id can be taken from the interface list from the section “Read current MTU in Windows” of this article. We found the MTU in the last paragraph. With the two values we can now set the MTU in the CMD with the following command.
The placeholders
MTU in OSX
Read current MTU in OSX
To read out the current MTU in OSX, either the network setting dialog or a short terminal command can be used. If the MTU shall be read out via the settings dialog, it can be found in “System Settings -> Network -> Additional Options -> Hardware”. On the hardware tab, set the configuration to “manual” and the MTU to “custom”. The MTU can then be read out. (Important: If the MTU shall be set by the system, the hardware dialog must be closed with “Cancel”!)
If the MTU shall be read out via the terminal, this can be done via the following shell command:
The value
Determine the optimal MTU in OSX
The determining the best MTU works (as also in Windows and Linux) by use of the ping command. For this purpose the parameters “D” and “s” must be set. The “D” parameter stands for “Do not fragment” and indicates that the package should not be fragmented. The “s” parameter specifies the size of the data packet. This initially hast to be set a little bit too large.
Now execute the command until the ping is successful. The “s” parameter must be reduced for each execution. If the ping is successful, add 28 to the “s” parameter value and take this sum as the MTU.
Set MTU value in OSX
To set the MTU in OSX, either the hardware dialog in the network settings (see paragraph “Reading current MTU in OSX”) or a command in the terminal can be used.
The value
MTU in Linux
Read current MTU in Linux
To display the current MTUs for network interfaces in Linux, the following command is suitable. (This must be entered in the shell/terminal.):
As a result, you should get a list of interfaces as well as their MTU values. At the beginning of the line is the respective identity, at the end of the line the MTU value.
If the command does not work, try the following command, which creates a similar list:
Those who prefer to click through dialogs instead of writing console commands can find the MTU in most Linux distributions also on the graphical interface. In Kubuntu for example the MTU can also be read out via the connection editor, as shown in the adjacent screenshot. In other distributions, there are similar paths/dialogs.
Determine the optimal MTU in Linux
In order to determine the optimal MTU value in Linux, the ping command is suitable – as is the case with Windows and OSX. However, the individual parameters differ slightly under Linux. The “c” parameter specifies how many pings should be sent. The “M” parameter with the value “do” indicates that the packages should not be fragmented in any case and the parameter “s” parameter specifies the size of the package.
Again, you start with an obviously too large data packet and gradually reduce the value until the ping is successful. If the packet is still too large, the following (or similar) error message appears: “ping: local error: Message too long”.
If the ideal packet size is found, 28 bytes (20 bytes TCP header, 8 bytes ICMP (Ping) header) must be added to get the MTU value.
Set the MTU value in Linux
To set the MTU in Linux, either GUI dialogs or shell commands can be used. If the MTU is to be set via the graphical interface, the same dialog, which we have used two paragraphs above to read the MTU, can be used.
If the MTU is to be set via the shell, this can be done with Debian/Ubuntu systems via the network interface config file. (Other distros may require other config steps.)
The individual interface configurations are located within the file. At the end of each interface configuration you can append
to set a fixed MTU value. The value