Keepalivetime type windows 10 registry value

SO_KEEPALIVE socket option

The SO_KEEPALIVE socket option is designed to allow an application to enable keep-alive packets for a socket connection.

To query the status of this socket option, call the getsockopt function. To set this option, call the setsockopt function with the following parameters.

Socket option value

The constant that represents this socket option is 0x0008.

Syntax

Parameters

A descriptor identifying the socket.

The level at which the option is defined. Use SOL_SOCKET for this operation.

The socket option for which the value is to be set. Use SO_KEEPALIVE for this operation.

A pointer to the buffer containing the value for the option to set. This parameter should point to buffer equal to or larger than the size of a DWORD value.

This value is treated as a boolean value with 0 used to indicate FALSE (disabled) and a nonzero value to indicate TRUE (enabled).

A pointer to the size, in bytes, of the optval buffer. This size must be equal to or larger than the size of a DWORD value.

Return value

If the operation completes successfully, setsockopt returns zero.

If the operation fails, a value of SOCKET_ERROR is returned and a specific error code can be retrieved by calling WSAGetLastError.

Error code Meaning
WSANOTINITIALISED A successful WSAStartup call must occur before using this function.
WSAENETDOWN The network subsystem has failed.
WSAEFAULT One of the optval or the optlen parameters point to memory that is not in a valid part of the user address space. This error is also returned if the value pointed to by the optlen parameter is less than the size of a DWORD value.
WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
WSAEINVAL The level parameter is unknown or invalid. On WindowsВ Vista and later, this error is also returned if the socket was in a transitional state.
WSAENOPROTOOPT The option is unknown or unsupported by the indicated protocol family. This error is returned if the socket descriptor passed in the s parameter was for a datagram socket.
WSAENOTSOCK The descriptor is not a socket.

Remarks

The getsockopt function called with the SO_KEEPALIVE socket option allows an application to retrieve the current state of the keepalive option, although this is feature not normally used. If an application needs to enable keepalive packets on a socket, it justs calls the setsockopt function to enable the option.

The setsockopt function called with the SO_KEEPALIVE socket option allows an application to enable keep-alive packets for a socket connection. The SO_KEEPALIVE option for a socket is disabled (set to FALSE) by default.

When this socket option is enabled, the TCP stack sends keep-alive packets when no data or acknowledgement packets have been received for the connection within an interval. For more information on the keep-alive option, see section 4.2.3.6 on the Requirements for Internet Hosts—Communication Layers specified in RFC 1122 available at the IETF website. (This resource may only be available in English.)

The SO_KEEPALIVE socket option is valid only for protocols that support the notion of keep-alive (connection-oriented protocols). For TCP, the default keep-alive timeout is 2 hours and the keep-alive interval is 1 second. The default number of keep-alive probes varies based on the version of Windows.

The SIO_KEEPALIVE_VALS control code can be used to enable or disable keep-alive, and adjust the timeout and interval, for a single connection. If keep-alive is enabled with SO_KEEPALIVE, then the default TCP settings are used for keep-alive timeout and interval unless these values have been changed using SIO_KEEPALIVE_VALS.

The default system-wide value of the keep-alive timeout is controllable through the KeepAliveTime registry setting which takes a value in milliseconds. The default system-wide value of the keep-alive interval is controllable through the KeepAliveInterval registry setting which takes a value in milliseconds.

On WindowsВ Vista and later, the number of keep-alive probes (data retransmissions) is set to 10 and cannot be changed.

On Windows ServerВ 2003, WindowsВ XP, and WindowsВ 2000, the default setting for number of keep-alive probes is 5. The number of keep-alive probes is controllable through the TcpMaxDataRetransmissions and PPTPTcpMaxDataRetransmissions registry settings. The number of keep-alive probes is set to the larger of the two registry key values. If this number is 0, then keep-alive probes will not be sent. If this number is above 255, then it is adjusted to 255.

On WindowsВ Vista and later, the SO_KEEPALIVE socket option can only be set using the setsockopt function when the socket is in a well-known state not a transitional state. For TCP, the SO_KEEPALIVE socket option should be set either before the connect function (connect, ConnectEx, WSAConnect, WSAConnectByList, or WSAConnectByName) is called, or after the connection request is actually completed. If the connect function was called asynchronously, then this requires waiting for the connection completion before trying to set the SO_KEEPALIVE socket option. If an application attempts to set the SO_KEEPALIVE socket option when a connection request is still in process, the setsockopt function will fail and return WSAEINVAL.

On Windows ServerВ 2003, WindowsВ XP, and WindowsВ 2000, the SO_KEEPALIVE socket option can be set using the setsockopt function when the socket is a transitional state (a connection request is still in progress) as well as a well-known state.

SIO_KEEPALIVE_VALS Control Code

Description

The SIO_KEEPALIVE_VALS control code enables or disables the per-connection setting of the TCP keep-alive option which specifies the TCP keep-alive timeout and interval.

To perform this operation, call the WSAIoctl or WSPIoctl function with the following parameters.

Parameters

A descriptor identifying a socket.

dwIoControlCode

The control code for the operation. Use SIO_KEEPALIVE_VALS for this operation.

lpvInBuffer

A pointer to the input buffer. This parameter should point to a tcp_keepalive structure.

cbInBuffer

The size, in bytes, of the input buffer. This parameter should equal to or greater than the size of the tcp_keepalive structure pointed to by the lpvInBuffer parameter.

lpvOutBuffer

A pointer to the output buffer. This parameter is unused for this operation.

cbOutBuffer

The size, in bytes, of the output buffer. This parameter must be set to zero.

lpcbBytesReturned

A pointer to a variable that receives the size, in bytes, of the data stored in the output buffer. This returned parameter points to a DWORD value of zero for this operation, since there is no output.

lpvOverlapped

If socket s was created without the overlapped attribute, the lpOverlapped parameter is ignored.

If s was opened with the overlapped attribute and the lpOverlapped parameter is not NULL, the operation is performed as an overlapped (asynchronous) operation. In this case, lpOverlapped parameter must point to a valid WSAOVERLAPPED structure.

For overlapped operations, the WSAIoctl or WSPIoctl function returns immediately, and the appropriate completion method is signaled when the operation has been completed. Otherwise, the function does not return until the operation has been completed or an error occurs.

lpCompletionRoutine

A pointer to the completion routine called when the operation has been completed (ignored for non-overlapped sockets).

lpThreadId

A pointer to a WSATHREADID structure to be used by the provider in a subsequent call to WPUQueueApc. The provider should store the referenced WSATHREADID structure (not the pointer to same) until after the WPUQueueApc function returns.

Note This parameter applies only to the WSPIoctl function.

lpErrno

A pointer to the error code.

Note This parameter applies only to the WSPIoctl function.

Return value

If the operation completes successfully, the WSAIoctl or WSPIoctl function returns zero.

If the operation fails or is pending, the WSAIoctl or WSPIoctl function returns SOCKET_ERROR. To get extended error information, call WSAGetLastError.

Error code Meaning
WSA_IO_PENDING An overlapped operation was successfully initiated and completion will be indicated at a later time.
WSA_OPERATION_ABORTED An overlapped operation was canceled due to the closure of the socket or the execution of the SIO_FLUSH IOCTL command.
WSAEFAULT The lpOverlapped or lpCompletionRoutine parameter is not totally contained in a valid part of the user address space.
WSAEINPROGRESS The function is invoked when a callback is in progress.
WSAEINTR A blocking operation was interrupted.
WSAEINVAL The dwIoControlCode parameter is not a valid command, or a specified input parameter is not acceptable, or the command is not applicable to the type of socket specified.
WSAENETDOWN The network subsystem has failed.
WSAENOPROTOOPT The socket option is not supported on the specified protocol. This error is returned for a datagram socket.
WSAENOTSOCK The descriptor s is not a socket.
WSAEOPNOTSUPP The specified IOCTL command is not supported. This error is returned if the SIO_KEEPALIVE_VALS IOCTL is not supported by the transport provider.

Remarks

The SIO_KEEPALIVE_VALS IOCTL is supported on Windows 2000 and later versions of the operating system.

The SIO_KEEPALIVE_VALS control code enables or disables the per-connection setting of the TCP keep-alive option which specifies the TCP keep-alive timeout and interval used for TCP keep-alive packets. For more information on the keep-alive option, see section 4.2.3.6 on the Requirements for Internet Hosts—Communication Layers specified in RFC 1122 available at the IETF website. (This resource may only be available in English.)

The lpvInBuffer parameter should point to a tcp_keepalive structure defined in the Mstcpip.h header file. This structure is defined as follows:

The value specified in the onoff member determines if TCP keep-alive is enabled or disabled. If the onoff member is set to a nonzero value, TCP keep-alive is enabled and the other members in the structure are used. The keepalivetime member specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent. The keepaliveinterval member specifies the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is received.

The SO_KEEPALIVE option, which is one of the SOL_SOCKET Socket Options, can also be used to enable or disable the TCP keep-alive on a connection, as well as query the current state of this option. To query whether TCP keep-alive is enabled on a socket, the getsockopt function can be called with the SO_KEEPALIVE option. To enable or disable TCP keep-alive, the setsockopt function can be called with the SO_KEEPALIVE option. If TCP keep-alive is enabled with SO_KEEPALIVE, then the default TCP settings are used for keep-alive timeout and interval unless these values have been changed using SIO_KEEPALIVE_VALS.

The default system-wide value of the keep-alive timeout is controllable through the KeepAliveTime registry setting which takes a value in milliseconds. If the key is not set, the default keep-alive timeout is 2 hours. The default system-wide value of the keep-alive interval is controllable through the KeepAliveInterval registry setting which takes a value in milliseconds. If the key is not set, the default keep-alive interval is 1 second.

On Windows Vista and later, the number of keep-alive probes (data retransmissions) is set to 10 and cannot be changed.

On Windows Server 2003, Windows XP, and Windows 2000, the default setting for number of keep-alive probes is 5. The number of keep-alive probes is controllable through the TcpMaxDataRetransmissions and PPTPTcpMaxDataRetransmissions registry settings. The number of keep-alive probes is set to the larger of the two registry key values. If this number is 0, then keep-alive probes will not be sent. If this number is above 255, then it is adjusted to 255.

Использование KEEPALIVE-сокетов для обнаружения и отключения зависших клиентских соединений InterBase и Firebird

Овчинников Василий, 17.05.2005, изменено – 06.09.2005.

Введение

В системах, предназначенных для работы в реальном времени или близком к нему, существует проблема отслеживания на серверной стороне состояния клиентских соединений и принятия мер для их принудительного отключения в случае недоступности клиента вследствие разрыва соединения. Особенно при использовании Classic Firebird SQL Server важно своевременно освобождать ресурсы, занимаемые такими фантомными соединениями.

Если имеются пользователи, подключающиеся к серверу через модемы, то достаточно велика вероятность обрыва модемного соединения в самый неподходящий момент.

Например, клиент сохраняет измененный набор записей. После выполнения UPDATE, но до выполнения COMMIT модемное соединение разрывается. Обычно клиентское приложение в такой ситуации восстанавливает соединение с сервером, но клиент, продолжая работу с теми же данными, при сохранении которых он получил сообщение об ошибке по причине разрыва соединения, не может сохранить свои изменения, получая со стороны сервера сообщение о конфликте блокировки. Ему мешает его предыдущее соединение, открывшее транзакцию, в контексте которой был выполнен UPDATE, но не был выполнен COMMIT, т. к. соединение со стороны клиента было разорвано.

Точно так же обрывы соединений могут возникать и в локальной сети, если сбоит оборудование – сетевые карты, хабы, коммутаторы – или возникают помехи. В interbase.log/firebird.log обрывы коннектов tcp показываются как ошибки 10054 (Windows. на Unix – 104), обрывы netbeui – как ошибки 108/109.

Для отслеживания и отключения таких «мертвых» соединений InterBase и Firebird использует один из двух механизмов – DUMMY-пакеты (реализован на прикладном уровне начиная с InterBase 5.0 между сервером InterBase/ Firebird и клиентской библиотекой gds32/fbclient, включается в ibconfig/firebird.conf и в данном документе рассматриваться не будет) и KEEPALIVE-сокеты (используется по умолчанию начиная с InterBase 6.0). Использование KEEPALIVE включается установкой опции сокета SO_ KEEPALIVE при его открытии. Вам не нужно специально заботиться об этом, если вы используете Firebird 1.5 или выше – это реализовано в программном коде сервера Firebird, как для Classic, так и для Superserver. Для InterBase и Firebird (младше 1.5) в варианте Classic (существуют только для Unix/ Linux) необходима дополнительная настройка (см. п. 3). В этом случае отслеживание состояния соединения возлагается не на сервер Firebird, а на стек TCP операционной системы. Однако для практического использования требуется настройка параметров KEEPALIVE.

Описание KEEPALIVE

Поведение KEEPALIVE-сокетов регулируется параметрами, представленными в таблице:

Параметр Описание
KEEPALIVE_ TIME Интервал времени, по истечении которого начинаются пробы KEEPALIVE
KEEPALIVE_INTERVAL Интервал времени между пробами KEEPALIVE
KEEPALIVE_PROBES Количество проб KEEPALIVE

Стек TCP отслеживает момент прекращения прохождения пакетов между клиентом и сервером, запуская таймер KEEPALIVE. Как только таймер достигнет величины KEEPALIVE_ TIME, стек TCP сервера выполняет первую пробу KEEPALIVE. Проба – это пустой пакет c флагом ACK, отправляемый клиенту. Если на стороне клиента все в порядке, то стек TCP на клиентской стороне посылает ответный пакет с флагом ACK и стек TCP сервера, получив ответ, сбрасывает таймер KEEPALIVE. Если клиент не отвечает на пробу, то пробы со стороны сервера продолжают выполняться. Их количество равно KEEPALIVE_ PROBES и выполняются они через интервал времени KEEPALIVE_ INTERVAL. Если клиент не ответил на последнюю пробу, то по истечении еще одного интервала времени KEEPALIVE_ INTERVAL стек TCP операционной системы сервера закрывает соединение и Firebird высвобождает все ресурсы, занимаемые обслуживанием данного соединения.

Таким образом, разорванное клиентское соединение будет закрыто по истечении времени KEEPALIVE_ TIME+ ( KEEPALIVE_ PROBES+1)* KEEPALIVE_ INTERVAL.

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

Ниже мы рассмотрим настройку этих параметров для операционных систем семейства Windows и операционной системы Linux.

Настройка KEEPAILVE в Linux

Параметры KEEPALIVE в Linux можно изменить либо прямым редактированием файловой системы / proc либо вызовами sysctl.

Для первого случая надо редактировать:

Время задается в секундах.

Для автоматической установки этих параметров в случае перезагрузки сервера добавьте в /etc/sysctl.conf:

Слово замените на нужные вам величины.

Если вы используете Firebird Classic ранее версии 1.5, то в /etc/xinet.d/firebird пропишите следующее:

Настройка KEEPALIVE в Windows 95/98/ME

Параметры:

  • KeepAliveTime = миллисекунды
  • KeepAliveInterval = 32-значное число
  • MaxDataRetries = 32-значное число

Настройка KEEPALIVE в Windows 2000/NT/XP

Настройка KEEPALIVE в Windows (для клиентов)

параметр DisableDHCPMediaSense=1. См. описание данного параметра здесь: http://support.microsoft.com/?scid =kb%3Bru%3B239924&x=13&y=14.

Рассмотрим пример настройки Firebird SQL Server 1.5.2 CS под ОС Linux:

  • Убедимся, что в firebird.conf отключен механизм DUMMY-пакетов (параметр закомментирован)
  • Убедимся в наличии конфигурационного файла /etc/xinet.d/firebird
  • Устанавливаем соединение к любой базе данных на сервере с любого сетевого клиента.
  • Смотрим трафик на сервере используя любой фильтр пакетов.
  • Если клиента отключить физически (выключить коммутатор или модем – мало ли, что может случиться в действительности), то на пробу сервера ответ от клиента не приходит, и сервер начинает с 10-ти секундным интервалом посылать пробы. Если на пятую пробу клиент не ответил, то еще через 10 секунд серверный процесс выгружается, освобождая ресурсы и блокировки. Если клиент подал признаки жизни и откликнулся хотя бы и на пятую пробу (худший случай), то снова выдерживается 15-сек тайм-аут и опять начинаются пробы. И т. д.

Заключение

В заключение хотелось бы привести практические рекомендации по выбору величин параметров KEEPALIVE.

Во-первых, определите для себя необходимую величину параметра KEEPALIVE_TIME. Чем больше будет его значение, тем позже начнутся KEEPALIVE-пробы. Если вы постоянно наблюдаете на своем сервере множество зависших коннектов, и вам приходится их удалять вручную, то следует уменьшить величину KEEPALIVE_TIME.

Во-вторых, значения параметров KEEPALIVE_INTERVAL и KEEPALIVE_PROBES должны удовлетворять вашим требованиям по своевременному отключению уже обнаруженных системой зависших соединений. Если ваши пользователи устанавливают соединения с сервером через ненадежные каналы связи, то вам, возможно, захочется увеличить количество проб и интервал между ними для того, чтобы пользователь успел обнаружить обрыв и восстановить соединение с сервером. В случае, если клиентоы используют выделенное подключение к сетям общего пользования (Интернет) или используют доступ к SQL-серверу по локальной сети, возможно уменьшение количества и интервала между KEEPALIVE-пробами.

Общие рекомендации могут звучать так: если вы на практике получаете большое количество сообщений от клиентов об ошибках сохранения результатов работы по причине конфликта блокировки без видимых на то причин, т. е. при отсутствии конкурирующих соединений, работающих с теми же данными, то вам надо увеличивать реакцию системы на отключение зависших коннектов. Практически величина KEEPALIVE_TIME может составлять от 1 минуты и более – вы сами должны оценить время выполнения самой длительной транзакции в системе, чтобы не перегружать сетевой трафик KEEPALIVE-проверками нормально работающих соединений, запустивших длительные транзакции. Величина KEEPALIVE_INTERVAL – от 10 секунд и более, а величина KEEPALIVE_PROBES – от 5 проверок и более. Помните, что большое количество проверок и малый интервал между ними могут существенно увеличить сетевой трафик при большом количестве одновременно работающих пользователей.

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

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

  • Клиенты используют модемные соединения, в системе преобладают короткие транзакции, время простоя ограничено 3 минутами.
Читайте также:  Heic to jpeg converter mac os
Оцените статью