Tcp windows size как узнать

Время на прочтение5 мин

Количество просмотров6.5K

Задержки (а по‑простому тормоза) в работе сети вряд ли кого‑то оставят равнодушным. Мы все очень не любим, когда медленно загружаются наши любимые веб‑ресурсы, или когда обрывается на 99% загрузка какого‑либо файла. Причин тормозов в сети может быть много — от проблем на физическом уровне и до медленной работы на уровне приложений. Сегодня мы поговорим об одной из причин задержек в сети, которую можно выявить с помощью анализатора пакета Wireshark. При этом не имеет особого значения, передается ли наш трафик в открытом виде или прячется за SSL: на верхние уровни мы забираться не будем. Важно только то, что это TCP трафик.

Окна в TCP

Протокол TCP содержит в своей архитектуре ряд функций, позволяющих препятствовать потере пакетов — например, такие механизмы, как повторные передачи и дублирующие подтверждения. Для предотвращения начала потери пакетов в TCP используется механизм скользящего окна (sliding‑window).

В механизме скользящего окна используется окно приема на стороне получателя пакетов для управления потоком данных. Принимающий хост указывает размер окна приема в байтах, сохраняет его в ТСР‑заголовке и сообщает передающему хосту, сколько данных он готов сохранить в памяти своего ТСР‑буфера. Именно в этой памяти данные временно хранятся до тех пор, пока они не будут переданы вверх по стеку протоколов на уровень приложений для последующей обработки. В итоге передающий хост может одновременно послать только то количество данных, которое указано в поле Window size (Размер окна) заголовка, полученного в ответ пакета ТСР. Чтобы передающий хост мог послать больше данных, принимающий хост должен отправить ему подтверждение о получении предыдущей порции данных. Он должен также очистить память своего ТСР‑буфера, обработав данные, занимающие эту память.

В целом, все достаточно просто. Принимающая сторона говорит, что готова принять, условно, три блока данных, отправитель передает их. Получает отправляет подтверждение, после чего отправляются следующие три блока данных и так далее.

В идеальном мире с постоянной пропускной способностью каналов размер окна действительно был бы постоянным значением. Однако, в реальности загрузка канала у нас постоянно меняется, и вместе с ней меняется и размер Window size. Процесс изменения размеров окна приема действует как в сторону уменьшения, так и увеличения. Так, если сервер способен обработать данные с большей скоростью, он может послать подтверждающий пакет АСК с большим размером окна приема.

Но ниже представлен пример приложения, у которого по каким‑то причинам уменьшился объем памяти, доступной в буфере, в результате чего получатель был вынужден уменьшить размер окна.

В случае, если получателю удалось решить свои проблемы с памятью, окно может быть снова увеличено. Но если быстро решить проблемы не удалось, и есть риск, что следующий блок данных обработать не удастся, получатель может указать размер Window=0. Что произойдет в таком случае?

Получив такой пакет, клиент прервет передачу данных и будет периодически отправлять пакет поддержания активным соединения. По сути, мы просто поддерживаем TCP соединение, при этом не передавая никаких данных. Когда получатель наконец‑то решит свои проблемы с памятью, он отправит пакет с обновлением размеров окна и передача полезной нагрузки продолжится.

От теории к практике

Теперь давайте вооружимся Wireshark и посмотрим, как выглядит соответствующий трафик.

В примере ниже у нас происходит информационный обмен между 192.168.0.20 и 192.168.0.30. В первых трех ACK пакетах значение Window уменьшается, видимо, у получателя проблемы с памятью и он не может обрабатывать больший объем данных.

Затем получатель отправляет пакет с нулевым окном. Однако после этого, по прошествии небольшого интервала времени, он отправляет обновление информации о размерах окна, в результате чего передача полезной нагрузки возобновляется.

В самом пакете информация о размере окна находится в TCP заголовке:

Теперь посмотрим более печальный случай: когда получателю не удается быстро решить свои проблемы с памятью и значение Window остается нулевым некоторое время.

Здесь мы видим обмен трафиком между двумя узлами. В какой‑то момент один из участников отказывается принимать полезную нагрузку, отправив TCP ZeroWindow. После этого второй участник обмена с некоторой периодичностью отправляет Keep‑Alive пакеты, на которые первый участник продолжает отвечать нулевыми окнами. Пакеты Keep‑Alive также являются служебными и не несут в себе никакой полезной нагрузки.

Как искать

В приведенных примерах наши служебные пакеты были представлены в уже отфильтрованном виде без лишнего трафика. В реальных дампах у нас будет много других пакетов, и нам потребуется осуществить фильтрацию.

Для того чтобы отфильтровать в Wireshark пакеты с определенным размером окна, нужно воспользоваться фильтром tcp.window_size_value.

Например, для того, чтобы найти все пакеты с ненулевым размером окна, нужно указать tcp.window_size_value > 0

Для фильтрации пакетов с ZeroWindow можно, конечно, явно указать фильтр tcp.window_size_value == 0, а можно воспользоваться фильтром

tcp.analysis.zero_window

Для обнаружения Keep_Alive воспользуемся фильтром tcp.analysis.keep_alive

Также узнать, как с течением времени менялось значение TCP Window, можно с помощью графика. Для этого нужно выбрать Statistics → TCP Stream Graph → Window Scaling.

Заключение

Механизм скользящего окна, о котором мы сегодня говорили, непосредственно связан с неспособностью сервера принимать и обрабатывать данные. Любое уменьшение размера окна приема или даже его установка в нулевое состояние является непосредственным результатом какого‑то затруднения, возникшего на сервере. Поэтому, если вы видите большое количество таких пакетов в трафике, то это верный признак проблем с производительностью на принимающем узле и возможная причина задержек и сбоев в работе сетевых приложений.

В завершение рекомендую открытые уроки в Otus, подробнее о них ниже. Занятия пройдут в онлайн-формате и будут полезны сетевым инженерам, сетевым архитекторам и всем, кто глубоко интересуется современными сетевыми технологиями.

  • 5 февраля: ISIS vs. OSPF, или почему же ISIS до сих пор проигрывает битву OSPF в корпоративных сетях? Записаться

  • 18 февраля: Надежность и сети, или почему скорость сходимости STP уже очень давно никому не нравится? Записаться

Iperf is a bandwidth testing tool that network engineers use for stress testing their networks. As we will this in this article, the maximum TCP bandwidth that iperf can achieve depends on many factors. Some users that need to generate more than 1 Gbps may need to use some iperf advanced options. In some cases, it may also be necessary to change some TCP/IP settings within their operating systems.

Factors impacting iperf TCP throughput

There are three main factors that impact iperf maximum TCP throughput:

  1. Interface: if you are using a Raspberry Pi that has a 10/100 interface, then the upper limit is 100 Mbps.
  2. CPU capabilities: pushing several Gbps of traffic needs quite a bit of CPU performance.
  3. Latency: the greater the latency between source and destination, the larger the TCP window size needs to be.

The interface and the CPU put hard limits on the maximum bandwidth you can achieve. You can’t bypass them unless you get new hardware. However, given your link’s latency, you can adjust the TCP window size in order to achieve the desired bandwidth. But it can be tricky …

Calculating the TCP window size

The maximum achievable bandwidth is equal to:

[TCP Window Size in bits] / [Latency in seconds] = [Throughput in bits per second]

Here is a calculator for getting the TCP window size. The default window size that iPerf uses varies by machine type and operating system. If it’s 64 KBytes, with a modest latency of 10 ms, the maximum bandwidth you can get is 52.43 Mbits/sec. For 50 ms the maximum is 10.49 Mbits/sec. The obvious option would be to increase the window size to a larger value and get up to, let’s say, 500 Mbps. For a 50 ms latency, the window size needs to be 3.1 Mbytes. Indeed, iPerf gives you the option to set the window size, but if you try to set it to 3.1 or 4.0 Mbytes you may get the following warning from iPerf:

“TCP window size: 416 KByte (WARNING: requested 4.00 MByte)”

Oops… Why didn’t iPerf follow your command and used only a 416 Kbyte window? The devil is in the details! In this case, the devil is the operating system that has a hard limit on the TCP window size that an application can use. It looks like in this case the limit is 416 Kbytes. These limits exist for good reasons. Larger TCP windows take more system memory and if you have multiple applications running, using large windows they may bog down the system. Or the system may deny TCP connections if it is running out of memory.

Changing the TCP window size on Linux

In your case, if you have full control of the system and you know what you are doing, you may want to increase the OS limits. As an example, to increase those limits to 4 MBytes, run the following commands as root on a Debian Linux machine:

echo 'net.core.wmem_max=4194304' >> /etc/sysctl.conf
echo 'net.core.rmem_max=12582912' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_rmem = 4096 87380 4194304' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_wmem = 4096 87380 4194304' >> /etc/sysctl.conf
sysctl -p

Now if you request iPerf to use a 4 Mbyte TCP window size, you will see that your request will get fulfilled like it’s supposed to.

More on Iperf and Throughput Testing

For some iperf basics, take a look at some of these past posts:

  • How can you measure bandwidth?
  • Raspberry Pi and Distributed Network Monitoring: Iperf
  • Network Monitoring with Iperf: Raspberry Pi vs. Odroid vs. Banana Pi vs. Utilite
  • How can you measure bandwidth?

Get your free trial
now

Monitor your network from the user perspective

Returns the receive window size of a TCP segment. This field specifies the number of bytes that the sender of the segment is currently willing to receive. Click here for more information and details.

How does it work in the search window?

Select Create field in the search window toolbar, then select the TCP window size operation. You need to specify one argument:

Argument

Data type

Packet mandatory

packet

The data type of the values in the new field is integer.

How does it work in LINQ?

Use the operator select… as…  and add the operation syntax to create the new field. This is the syntax for the TCP window size operation:

  • tcpwin(packet)

Transmission Control Protocol (TCP) is a fundamental protocol used in computer networks to ensure reliable data transmission. One crucial aspect of TCP performance is throughput, which measures the rate at which data can be transferred across a network. Understanding TCP throughput calculations is essential for optimizing network efficiency and ensuring smooth data flow. This article will delve into the concept of TCP throughput, explain the factors affecting it, and present methods for calculating and maximizing throughput.

  1. Understanding TCP Throughput

TCP throughput refers to the amount of data that can be transmitted over a network in a given time frame. It is measured in bits per second (bps) and is influenced by various factors, including network bandwidth, latency, packet loss, and the TCP window size.

Network Bandwidth:

The available bandwidth is the maximum data rate that the network can support. It is typically measured in Mbps (Megabits per second) or Gbps (Gigabits per second). The network bandwidth serves as a theoretical upper limit for the TCP throughput.

Latency: Latency represents the time it takes for a data packet to travel from the source to the destination. It is usually measured in milliseconds (ms). Higher latency can impact TCP throughput, especially for applications that require low response times.

Packet Loss: Packet loss occurs when data packets are dropped during transmission. It can be caused by network congestion or errors in the network. Packet loss can significantly reduce TCP throughput and result in retransmissions, affecting overall performance.

TCP Window Size: The TCP window size determines the amount of data a sender can transmit before receiving an acknowledgment from the receiver. A larger window size can improve throughput by allowing more data to be sent before waiting for acknowledgment.

  1. Calculating TCP Throughput

TCP throughput can be estimated using the following formula:

Throughput (bps) = TCP Window Size (bits) / Round-Trip Time (seconds)

The round-trip time (RTT) is the time it takes for a small data packet to travel from the sender to the receiver and back. It includes both the time taken for data transmission and the acknowledgment to return.

Example:

Let’s consider a TCP connection with a TCP window size of 64,000 bits and an RTT of 0.2 seconds.

Throughput = 64,000 bits / 0.2 seconds = 320,000 bps

  1. Factors Affecting TCP Throughput

a. Bandwidth Delay Product (BDP):

The BDP is the maximum amount of data that can be in transit on the network at any given time. It is calculated by multiplying the bandwidth (in bps) by the round-trip time (in seconds). The TCP window size should be set to a value close to the BDP to achieve optimal throughput.

b. Congestion Window (CWND):

The CWND is dynamically adjusted by TCP to control the amount of data that can be sent before waiting for acknowledgments. It helps to avoid network congestion. When the CWND is small, the throughput may be limited, but it increases as the CWND grows.

c. TCP Slow Start:

During the initial phase of a TCP connection, the sender starts with a small CWND and increases it exponentially. This process, called slow start, helps avoid overwhelming the network with too much data at once.

  1. Methods to Maximize TCP Throughput

a. Increasing TCP Window Size:

By increasing the TCP window size, more data can be sent before waiting for acknowledgments. However, setting the window size too large can lead to congestion and packet loss. Balancing the window size with the BDP is crucial for optimizing throughput.

b. Path MTU Discovery:

Path Maximum Transmission Unit (MTU) discovery helps determine the largest packet size that can be transmitted across the network without fragmentation. Using the optimal MTU size can reduce overhead and improve throughput.

c. TCP Offload Engines (TOE):

TOEs are specialized hardware components that handle TCP processing, relieving the burden from the main CPU. This can improve overall system performance and, in turn, enhance TCP throughput.

d. Quality of Service (QoS) Implementation:

QoS mechanisms prioritize specific traffic types, ensuring critical data receives sufficient network resources. This prevents congestion and packet loss, leading to better throughput for prioritized applications.

Let’s explore more examples of TCP throughput calculations in different scenarios:

Example 1:

High Bandwidth, Low Latency Connection Consider a scenario where you have a high-speed network connection with a bandwidth of 1 Gbps (1,000,000,000 bps) and a low latency of 5 milliseconds (0.005 seconds).

Let’s calculate the TCP throughput using the formula:

Throughput = TCP Window Size / Round-Trip Time

Suppose the TCP window size is set to 1,048,576 bits (128 KB).

Throughput = 1,048,576 bits / 0.005 seconds ≈ 209,715,200 bps or 209.7 Mbps

In this example, the high bandwidth and low latency result in a significant TCP throughput, allowing for fast data transmission.

Example 2:

TCP Throughput with High Packet Loss Now, let’s consider a scenario where the network experiences high packet loss, which adversely affects TCP throughput. Suppose we have a bandwidth of 100 Mbps (100,000,000 bps), a round-trip time of 50 milliseconds (0.05 seconds), and a TCP window size of 32,768 bits (4 KB). Due to network congestion, 10% of the packets are lost during transmission.

Effective TCP Window Size = TCP Window Size * (1 – Packet Loss Percentage) Effective TCP Window Size = 32,768 bits * (1 – 0.10) = 29,491.2 bits (approximately 3.68 KB)

Throughput = Effective TCP Window Size / Round-Trip Time

Throughput = 29,491.2 bits / 0.05 seconds ≈ 589,824 bps or 0.59 Mbps

The high packet loss significantly reduces the effective TCP window size and, consequently, the throughput.

Example 3:

Impact of TCP Window Size on Throughput Let’s examine how different TCP window sizes affect throughput with a 10 ms round-trip time and a bandwidth of 100 Mbps.

a. TCP Window Size = 64,000 bits (8 KB)

Throughput = 64,000 bits / 0.01 seconds = 6,400,000 bps or 6.4 Mbps

b. TCP Window Size = 128,000 bits (16 KB)

Throughput = 128,000 bits / 0.01 seconds = 12,800,000 bps or 12.8 Mbps

c. TCP Window Size = 256,000 bits (32 KB)

Throughput = 256,000 bits / 0.01 seconds = 25,600,000 bps or 25.6 Mbps

d. TCP Window Size = 512,000 bits (64 KB)

Throughput = 512,000 bits / 0.01 seconds = 51,200,000 bps or 51.2 Mbps

In this example, increasing the TCP window size results in a linear improvement in throughput. A larger window size allows for more data to be transmitted before waiting for acknowledgments, effectively utilizing the available bandwidth.

Conclusion

TCP throughput calculations are crucial for understanding and optimizing network performance. By considering different examples with varying network conditions and TCP settings, network administrators can fine-tune their systems to achieve the best possible throughput. Improving TCP throughput leads to faster data transfers, reduced response times, and enhanced overall network efficiency.

Table of Contents

TCP Window Size, Checksum & Urgent Pointer

The window, checksum and urgent pointer are another important fields in TCP header. Each of these fields are 2 bytes long. Now, let’s focus on these parts one by one and learn these details of TCP Header. We will start with TCP Window Size.


Window Size

Window size the most important part in the TCP header. This fields is used by the receiver to indicate to the sender, the amouth of data that it can accept. So, this field is very important for efficient data transfer and flow control.

Window size uses byte as a metric. If it is mentined that window size is 60k, then it means that receiver accept 60 kilobyte data. When the data transmitted reaches window value then sender expect another window value from the receiver along with the acknowledgement for the window just received.

Window size is not a random value. It is calculated with some parameters like below:

TCP Window Size Calculation

Here, with the link bandwidth and the avarage RTT between the receiver and the sender, the window size can be calculated as mentined above. For th case above, lets calculate the exact value.

BW=10 Mbit
Delay(Avarage RTT) = 10 ms

Window Size = BW (10000000) x Delay(0.01)
= 100000 bit
= (100000/8)/1024
= 12,5 kbyte is equal to nine 1460 byte segments

TCP Header, Acknowledgement of previous window, TCP windowing mechanism, TCP ACK mechanism

Window size is important for efficient data transfer, but it is not the only duty of window size. It also provides flow control.

By default 63 bytes window size is used. But the link monitored and some small increase or decrease can made to optimize this size. This is called “automatic self correcting mechanism”.

In the case when window size falls to zero, then the remote TCP can not send data until receiving another window size.

Think about a host connection to a web server. Web server needs small amouth of memory (RAM) different than the client session. This memory size is equal to window size. And this is dependent to tha bandwidth and delay between host and the web server.


Checksum

Checksum field provides the data to reach error-free to the correct destination. For this purpose an extra header called “pseudo header” is used.

Here, let’s talk about pseudo header a little. The pseudo header is a combination of five fields. These fields are 32 bit source ip address, 32 bit destination ip address, 8 bit zeros, 8 bit protocol field and 8 bit TCP length. Totaly 88 bits or 11 bytes.

TCP Checksum Calculation

When the packet received from the layer 4 of the receiver, then this value is calculated again and compared with the sender version. If the values are the same, then it is handled by application. If the values are different, then the packet is dropped and a notification is sent. This is done for every single packet.

The checksum field is zero at the initial calculation.Because it is a unknown. When the value is calculated then it changed with 0.


Urgent Pointer

Here we will recall some information that we discuss before. This is urgent pointer flag. As I mentined before, with urgent pointer flag, the data is signed as urgent. And with the urgent pointer field, the exact end of this urgent data is determined. Here urgent pointer field contains the address of the urgent data ends.

TCP Urgent Pointer

 

From the point of security, urgent pointer flag set can be used by attackers. Because some system guards do not check the packets that has urgent pointer flag set. This is a security vulnerability.

That’s all for these parameters… Let’s go the the last part of the TCP header article series…


Comparison of UDP and TCP Protocols!


Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Заглушка windows winhlp32 что это
  • Как узнать пароль для wifi на windows 10
  • Автовыключение ноутбука windows 10
  • Windows com stopcode код остановки unexpected store exception
  • Частная сеть без доступа к интернету windows 10