Tcp window full windows

Какие параметры влияют на производительность приложений? Часть 1. TCP Window Size

Самый простой способ понять значение термина размер TCP окна (TCP Window Size), это представить разговор двух человек. Один человек говорит, а второй кивает головой или говорит да, тем самым подтверждая, что он понял, а по сути, получил все слова, которые ему были сказаны. После этого разговор продолжается. Если мы встречаем особо говорливого человека, то наша голова быстро загружается, и мы начинаем терять нить разговора или переспрашивать нашего собеседника. Тоже самое происходит и в Матрице — в мире цифр и машин.

Размер TCP окна (TCP Window Size) – количество октетов (начиная с номера подтверждения), которое принимающая сторона готова принять в настоящий момент без подтверждения. На стадии установления соединения рабочая станция и сервер обмениваются значениями максимального размера TCP окна (TCP Window Size), которые присутствуют в пакете и эти значения можно легко увидеть, воспользовавшись захватом трафика.

Например, если размер окна получателя равен 16384 байта, то отправитель может отправить 16384 байта без остановки. Принимая во внимание, что максимальная длина сегмента (MSS) может быть 1460 байт, то отправитель сможет передать данный объем в 12 фреймах, и затем будет ждать подтверждение доставки от получателя и информации по обновлению размера окна. Если процесс прошел без ошибок, то размер окна может быть увеличен. Таким образом, реализуется размер скользящего окна в стеке протокола TCP.

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

Для расчёта максимального размера окна (т.е. максимальный объем данных, которые могут передаваться одним пользователем другому в канале связи) рассчитывается по формуле:

Полоса пропускания (бит/сек) * RTT (круговое время передачи по сети) = размер окна в битах

Таким образом, если ваши два офиса соединяет канал связи в 10 Мбит/сек и круговое время составляет 85 миллисекунд, то воспользовавшись данной формулой, мы получим значение окна равное:

10 000 000 * 0,085 / 8 = 106250 байт

Размер поля Window в заголовке TCP составляет 16 бит; это означает, что узел TCP может указать максимальный размер TCP окна 65535 байт. Таким образом, максимальная пропускная способность составляет:

65535 * 8 / 0,085 = 6,2 Мбит/сек

т.е. чуть больше 50% от реально доступной полосы пропускания канала.

В современных версиях операционных систем можно увеличить размер окна TCP Window Size и включить динамическое изменение окна в зависимости от состояния канала связи. В предложении RFC 1323 дано определение масштабирования окон, позволяющего получателю указывать размер окна больше 65535 байт, что позволит применять большие размеры окон и высокоскоростные каналы передачи. Параметр TCP Window Scale указывает коэффициент масштабирования окна, который в сочетании с 16-битным полем Window в заголовке TCP может увеличивать размер окна приема до максимального значения, составляющего примерно 1 ГБ. Параметр Window Scale отправляется только в сегментах синхронизации (SYN) при установке соединения. На нашем скриншоте из WireShark он составляет 256. Устройства, общающиеся друг с другом, могут указывать разные коэффициенты масштабирования для TCP окон.

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

Читайте также:  Azur lane mac os

Why would “TCP Full Window” happen?

I understand that «TCP Full Window» indicates that the sender is sending more data than receiver’s advertised window size? But why would this happen? Shouldn’t the sender just be able to send data window full

asked 09 Sep ’13, 22:30

SteveZhou
191 ● 27 ● 30 ● 34
accept rate: 0%

Shouldn’t the sender just be able to send data Kurt Knochner ♦
24.8k ● 10 ● 39 ● 237
accept rate: 15%

edited 10 Sep ’13, 00:09

what does the «allowed amount of data» mean here? The amount of data queued in the TCP send buffer? As i know, TCP send buffer won’t be allowed > advertised receiver window by its session peer.

what does the «allowed amount of data» mean here?

  • The Receiver advertises a TCP Window of 5000 byte.
  • The Sender sends 5 packets with a TCP Len of 1000 each
  • There is no ACK between those 5 packets
  • Wireshark will mark the 5th packet with [TCP Window Full] as it has seen those advertized 5000 bytes, without an ACK

Up to now, everything is O.K. as the sender did not ‘violate’ any convention. Now, it would be up to the receiver to send either an ACK, a ZeroWindow or a Window Update. If neither happens and the sender continues to send data, then there would be a problem.

According to the code, Wireshark will only print that message if it has seen exactly the amount of bytes on the line (without ACK) that have been advertised be the receiver. If the sender sends more bytes (for whatever reason), e.g. 1200 in the last packet of the example above, the frame will not be marked with [TCP Window Full].

very clear explanation! I understood. thank you!

What can I do to avoid TCP Zero Window/ TCP Window Full on the receiver side?

I have a small application which sends files over the network to an agent located on a Windows OS.

When this application runs on Windows, everything works fine, the communication is OK and the files are all copied successfully.

But, when this application runs on Linux (RedHat 5.3, the receiver is still Windows) — I see in Wireshark network trace messages of TCP Zero Window and TCP Window Full to appear on each 1-2 seconds. The agent then closes the connection after some minutes.

The Windows — Linux code is almost the same, and pretty simple. The only non-trivial operation is setsockopt with SO_SNDBUF and value of 0xFFFF. Removing this code didn’t help.

Can someone please help me with this issue?

EDIT: adding the sending code — it looks that it handles properly partial writes:

Thanks in advance.

0.5 GB, sometimes

1.3 GB of data and then fails. – rkellerm Aug 8 ’10 at 8:36

4 Answers 4

Not seeing your code I’ll have to guess.

The reason you get a Zero window in TCP is because there is no room in the receiver’s recv buffer.

There are a number of ways this can occur. One common cause of this problem is when you are sending over a LAN or other relatively fast network connection and one computer is significantly faster than the other computer. As an extreme example, say you’ve got a 3Ghz computer sending as fast as possible over a Gigabit Ethernet to another machine that’s running a 1Ghz cpu. Since the sender can send much faster than the receiver is able to read then the receiver’s recv buffer will fill up causing the TCP stack to advertise a Zero window to the sender.

Читайте также:  Что такое дискета для сброса пароля windows 10

Now this can cause problems on both the sending and receiving sides if they’re not both ready to deal with this. On the sending side this can cause the send buffer to fill up and calls to send either to block or fail if you’re using non-blocking I/O. On the receiving side you could be spending so much time on I/O that the application has no chance to process any of it’s data and giving the appearance of being locked up.

Edit

From some of your answers and code it sounds like your app is single threaded and you’re trying to do non-Blocking sends for some reason. I assume you’re setting the socket to non-Blocking in some other part of the code.

Generally, I would say that this is not a good idea. Ideally, if you’re worried about your app hanging on a send(2) you should set a long timeout on the socket using setsockopt and use a separate thread for the actual sending.

SO_RCVTIMEO and SO_SNDTIMEO Specify the receiving or sending timeouts until reporting an error. The parameter is a struct timeval. If an input or output function blocks for this period of time, and data has been sent or received, the return value of that function will be the amount of data transferred; if no data has been transferred and the timeout has been reached then -1 is returned with errno set to EAGAIN or EWOULDBLOCK just as if the socket was specified to be nonblocking. If the timeout is set to zero (the default) then the operation will never timeout.

Your main thread can push each file descriptor into a queue using say a boost mutex for queue access, then start 1 — N threads to do the actual sending using blocking I/O with send timeouts.

Your send function should look something like this ( assuming you’re setting a timeout ):

The MSG_NOSIGNAL flag ensures that your application isn’t killed by writing to a socket that’s been closed or reset by the peer. Sometimes I/O operations are interupted by signals, and checking for EINTR allows you to restart the send .

Generally, you should call doSend in a loop with chunks of data that are of TCP_MAXSEG size.

On the receive side you can write a similar blocking recv function using a timeout in a separate thread.

Tcp window full windows

Is there any update about the issue?

Jeremy Wu
TechNet Community Support

Many thanks for your kind follow-up. Just to share some update here. I didn’t perform the changes on the registry yet. But rather I have reduce the size of the download and the problem goes away. But in long run I believe the problem will come back again. I am waiting some approval to perform the changes. I shall let you know again.

I would like to check with you regarding to the path HKLM\System\CurrentControlSet\Services\Tcpip\Parameters\Interface\InterfaceGUID\TCPWindowSize. You have mention about the interfaceGUID, since in the machine I did see few of the interface. It is OK just to focus on the GUID where the IP address of the server is configure?. Looking forward on your reply.

Just to jump in, I agree with Jeremy about altering the TCPWIN size, but just to point out, in many cases Windows handles this automatically. The only time couple of times I’ve seen where I needed to alter it is when I was on a SLIP dialup in the early 90’s using a dialer on Win 3.11, and later on when I ran an FTP server many years ago on a cable line (when I was part of the cable high-speed beta program for my local cable company in the mid 90’s), so I manually increased it to 65k, which optimized large file transfers so CDROM sized file flew across nicely, but it caused issues with VPN clients, since they are on a slow line and a 65k WIN size was way beyond the WIN size a PPP connection can handle. So the point is to be careful on setting it and monitor the changes being proactive if anything occurs due to the change.

Читайте также:  Как установить linux с биоса

And if reducing the size of the download (you didn’t post what size it was and what you reduced it to), maybe the better option, or more specifically, it could be a setting in the app you’re using to download the large file, so we can leave Windows to auto-configure the TCPWIN size.

Ace Fekay
MVP, MCT, MCITP/EA, MCTS Windows 2008/R2 & Exchange 2007, Exchange 2010 EA, MCSE & MCSA 2003/2000, MCSA Messaging 2003
Microsoft Certified Trainer
Microsoft MVP — Directory Services
Technical Blogs & Videos: http://www.delawarecountycomputerconsulting.com/

This post is provided AS-IS with no warranties or guarantees and confers no rights.

TCP Window Full STM32

I’m developing an ethernet application on an stm32 nucleo board using the LWIP library and I’m getting a TCP Window Full message when my board is receiving data as you can see at the Wireshark capture. I`ve tested several times and I´ve realized that it stops working when the window arrives to 2144 bytes.

Does anyone know how to clean/reset this window? I know that I could increase this number as you can see at the second photo but i would prefer to be able to reset o clean it after a while because if not I would full the memory in a few minutes.

Thanks in advance 😉

WhireShark Capture:

STM32CubeMX capture of the LWIP Configuration:

1 Answer 1

«TCP Window Full» happens when your receive window shrinks down to zero, that is — the receive buffers get filled up. It will remain full until you receive the data from the socket.

It typically happens when the sender sends data faster than the receiver processes it, or at least receives it from the socket. When this happens, sender should stop sending more data until receiver is able to again receive more. This happens after you receive data from the socket and there’s two ways in which the sender is informed about it:

Receiver sends «TCP Window Update» which indicates how much space in the receive window is available again. This is not a frame that is acknowledged by the sender, it may get lost. Because of this there’s also a second way below.

Sender continually polls the receiver by sending TCP Keep-Alive packets (packets with no data). Those packets must be acknowledged by the receiver and because each TCP frame contains the remote end’s window size in its header, this way the sender is able to get the information whether you’re able to receive again.

«TCP Window Full» is not an error — Wireshark colors it in black just to indicate that if you have issues with transmission, this may be something you might want to look at. Another example of such coloring is TCP retransmissions.

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