Отсутствуют сетевые протоколы — ошибка Windows Sockets в Windows 10
У коллеги на домашнем компьютере с Windows 10 стал периодически (раз в 2-3 дня) пропадать доступ в интернет (статус “Ограничено” у подключения), а при запуске мастера диагностики сетей Windows (запускается при щелчке мыши по значку с ошибкой сетевого подключения или через Параметры -> Обновление и безопасность -> Устранение неполадок -> Запустить средство устранения неполадок подключения к Интернету) появляется характерная ошибка:
В реестре отсутствуют записи для Windows Sockets, необходимые для связи по сети.
Windows Sockets registry entries required for network connectivity are missing.
Коллега обычно решал проблему перезагрузкой Windows и роутера, после чего подключение в интернет работало какое-то время, но через день-два проблема повторялась. Недавно он попросил меня попробовать исправить ошибку с отсутствующими сетевыми протоколами. Вот что получилось у меня.
При такой плавающей проблеме обычно рекомендуется начать с самого простого — сбросить текущие настройки TCP/IP и Windows Sockets. Если у вас на компьютере IP адрес настроен вручную, а не через DHCP, следующие команды сбросят ваши сетевые настройки. Поэтому предварительно нужно записать текущие настройки IP адреса, маски, шлюза и DNS серверов для ваших сетевых подключений.
netsh winsock reset
netsh interface ipv4 reset
Данные команды сбросят настройки протокола TCP/IP для всех сетевых адаптеров и все обработчики (Winsock Layered Service Providers) к начальному, чистому состоянию. В результате вы удалите все сторонние обработчики, которые были встроены в ваш стек Winsock сторонними программами. Чаще всего в стек Winsock встраивают свои библиотеки-обработчики антивирусы, сниферы, файерволами и даже некоторые вирусы :).
После выполнения всех команду нужно перезагрузить компьютер и проверить интернет-подключение.
Если проблема не решилась, нужно через реестр удалить текущие настройки Windows Sockets.
- Откройте редактор реестра и перейдите к ключу HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WinSock. Создайте резервную копию ветки реестра, экспортировав ее в reg файл (ПКМ -> Export);
- Удалите ветку (ПКМ -> Delete);
- Выполните эти же действия для ветки HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Winsock2;
После этого вам нужно вручную переустановить компоненты протокола TCP/IP.
- В панели управления сетевыми подключениями (ncpa.cpl) откройте свойства вашего сетевого адаптера и нажмите кнопку Install;
- Выберите Protocol в списке компонентов для установки (Select Network Feature Type);
- Затем выберите, что вы хотите установить компонент с диска и укажите путь к каталогу C:\Windows\INF ;
- В списоке переустанавливаемых сетевых протоколов выберите Internet Protocol version 4 (TCP/IPv4) и перезагрузите компьютер.
.
Чтобы исправить ошибку нужно вручную импортировать с другого компьютера с той же версий ОС и применить на проблемном ПК следующие ветки реестра: HKLM\SYSTEM\CurrentControlSet\Services\Winsock и HKLM\SYSTEM\CurrentControlSet\Services\Winsock2.
Можете скачать готовые файлы для чистой Windows 10 x64 LTSC по ссылкам ниже:
После импорта reg файлов нужно перезагрузить компьютер и попробовать еще раз переустановить протокол TCP/IP (в самом крайнем случаем воспользуютесь своими ветками ресстра winsock, сохранными ранее, но лучше использовать чистые).
Теперь в свойствах вашего сетевого подключений проверьте, что он настроен на получение динамического IP адреса и настроек DNS серверов, либо укажите IP адрес и DNS сервера вручную (в моем случае после сброса статические настройки IP просто очистились ). Для домашнего компьютера можно указать использовать следующие статические адреса DNS серверов Google: 8.8.8.8 и 8.8.4.4.
Здесь же нажмите на кнопку Advanced и на вкладке WINS отключите просмотр LMHOSTS и NetBIOS через TCP/IP. Эти сетевые ротоколы являются устаревшими и не нужны в современных сетях .
После этого проблема с периодическим отключением интернета с ошибкой “отсутствуют один или несколько сетевых протоколов” в Windows 10 исчезла. Если вам и это не помогло, я бы попробовал дополнительно переустановить (обновить) драйвера ваших сетевых адаптеров. Возможно проблема еще и с ними.
WSAConnect function (winsock2.h)
The WSAConnect function establishes a connection to another socket application, exchanges connect data, and specifies required quality of service based on the specified FLOWSPEC structure.
Syntax
Parameters
A descriptor identifying an unconnected socket.
A pointer to a sockaddr structure that specifies the address to which to connect. For IPv4, the sockaddr contains AF_INET for the address family, the destination IPv4 address, and the destination port. For IPv6, the sockaddr structure contains AF_INET6 for the address family, the destination IPv6 address, the destination port, and may contain additional flow and scope-id information.
The length, in bytes, of the sockaddr structure pointed to by the name parameter.
A pointer to the user data that is to be transferred to the other socket during connection establishment. See Remarks.
A pointer to the user data that is to be transferred back from the other socket during connection establishment. See Remarks.
A pointer to the FLOWSPEC structures for socket s, one for each direction.
Reserved for future use with socket groups. A pointer to the FLOWSPEC structures for the socket group (if applicable). This parameter should be NULL.
Return value
If no error occurs, WSAConnect returns zero. Otherwise, it returns SOCKET_ERROR, and a specific error code can be retrieved by calling WSAGetLastError. On a blocking socket, the return value indicates success or failure of the connection attempt.
With a nonblocking socket, the connection attempt cannot be completed immediately. In this case, WSAConnect will return SOCKET_ERROR, and WSAGetLastError will return WSAEWOULDBLOCK; the application could therefore:
- Use select to determine the completion of the connection request by checking if the socket is writeable.
- If your application is using WSAAsyncSelect to indicate interest in connection events, then your application will receive an FD_CONNECT notification when the connect operation is complete(successful or not).
- If your application is using WSAEventSelect to indicate interest in connection events, then the associated event object will be signaled when the connect operation is complete (successful or not).
For a nonblocking socket, until the connection attempt completes all subsequent calls to WSAConnect on the same socket will fail with the error code WSAEALREADY.
If the return error code indicates the connection attempt failed (that is, WSAECONNREFUSED, WSAENETUNREACH, WSAETIMEDOUT) the application can call WSAConnect again for the same socket.
Error code | Meaning |
---|---|
WSANOTINITIALISED | A successful WSAStartup call must occur before using this function. |
WSAENETDOWN | The network subsystem has failed. |
WSAEADDRINUSE | The local address of the socket is already in use and the socket was not marked to allow address reuse with SO_REUSEADDR. This error usually occurs during the execution of bind, but could be delayed until this function if the bind function operates on a partially wildcard address (involving ADDR_ANY) and if a specific address needs to be «committed» at the time of this function. |
WSAEINTR | The (blocking) Windows Socket 1.1 call was canceled through WSACancelBlockingCall. |
WSAEINPROGRESS | A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. |
WSAEALREADY | A nonblocking connect or WSAConnect call is in progress on the specified socket. |
WSAEADDRNOTAVAIL | The remote address is not a valid address (such as ADDR_ANY). |
WSAEAFNOSUPPORT | Addresses in the specified family cannot be used with this socket. |
WSAECONNREFUSED | The attempt to connect was rejected. |
WSAEFAULT | The name or the namelen parameter is not a valid part of the user address space, the namelen parameter is too small, the buffer length for lpCalleeData, lpSQOS, and lpGQOS are too small, or the buffer length for lpCallerData is too large. |
WSAEINVAL | The parameter s is a listening socket, or the destination address specified is not consistent with that of the constrained group to which the socket belongs, or the lpGQOS parameter is not NULL. |
WSAEISCONN | The socket is already connected (connection-oriented sockets only). |
WSAENETUNREACH | The network cannot be reached from this host at this time. |
WSAEHOSTUNREACH | A socket operation was attempted to an unreachable host. |
WSAENOBUFS | No buffer space is available. The socket cannot be connected. |
WSAENOTSOCK | The descriptor is not a socket. |
WSAEOPNOTSUPP | The FLOWSPEC structures specified in lpSQOS and lpGQOS cannot be satisfied. |
WSAEPROTONOSUPPORT | The lpCallerData parameter is not supported by the service provider. |
WSAETIMEDOUT | Attempt to connect timed out without establishing a connection. |
WSAEWOULDBLOCK | The socket is marked as nonblocking and the connection cannot be completed immediately. |
WSAEACCES | Attempt to connect datagram socket to broadcast address failed because setsockopt SO_BROADCAST is not enabled. |
Remarks
The WSAConnect function is used to create a connection to the specified destination, and to perform a number of other ancillary operations that occur at connect time. If the socket, s, is unbound, unique values are assigned to the local association by the system, and the socket is marked as bound.
For applications targeted to WindowsВ Vista and later, consider using the WSAConnectByList or WSAConnectByName function which greatly simplify client application design.
For connection-oriented sockets (for example, type SOCK_STREAM), an active connection is initiated to the foreign host using name (an address in the namespace of the socket; for a detailed description, please see bind). When this call completes successfully, the socket is ready to send/receive data. If the address parameter of the name structure is all zeroes, WSAConnect will return the error WSAEADDRNOTAVAIL. Any attempt to reconnect an active connection will fail with the error code WSAEISCONN.
For a connectionless socket (for example, type SOCK_DGRAM), the operation performed by WSAConnect is merely to establish a default destination address so that the socket can be used on subsequent connection-oriented send and receive operations (send, WSASend, recv, and WSARecv). Any datagrams received from an address other than the destination address specified will be discarded. If the entire name structure is all zeros (not just the address parameter of the name structure), then the socket will be disconnected. Then, the default remote address will be indeterminate, so send, WSASend, recv, and WSARecv calls will return the error code WSAENOTCONN. However, sendto, WSASendTo, recvfrom, and WSARecvFrom can still be used. The default destination can be changed by simply calling WSAConnect again, even if the socket is already connected. Any datagrams queued for receipt are discarded if name is different from the previous WSAConnect.
For connectionless sockets, name can indicate any valid address, including a broadcast address. However, to connect to a broadcast address, a socket must have setsockopt SO_BROADCAST enabled. Otherwise, WSAConnect will fail with the error code WSAEACCES.
On connectionless sockets, exchange of user-to-user data is not possible and the corresponding parameters will be silently ignored.
The application is responsible for allocating any memory space pointed to directly or indirectly by any of the parameters it specifies.
The lpCallerData parameter contains a pointer to any user data that is to be sent along with the connection request (called connect data). This is additional data, not in the normal network data stream, that is sent with network requests to establish a connection. This option is used by legacy protocols such as DECNet, OSI TP4, and others.
If lpCallerData is NULL, no user data will be passed to the peer. The lpCalleeData is a result parameter that will contain any user data passed back from the other socket as part of the connection establishment in a WSABUF structure. The len member of the WSABUF structure pointed to by the lpCalleeData parameter initially contains the length of the buffer allocated by the application for the buf member of the WSABUF structure. The len member of the WSABUF structure pointed to by the lpCalleeData parameter will be set to zero if no user data has been passed back. The lpCalleeData information will be valid when the connection operation is complete. For blocking sockets, the connection operation completes when the WSAConnect function returns. For nonblocking sockets, completion will be after the FD_CONNECT notification has occurred. If lpCalleeData is NULL, no user data will be passed back. The exact format of the user data is specific to the address family to which the socket belongs.
At connect time, an application can use the lpSQOS and lpGQOS parameter to override any previous quality of service specification made for the socket through WSAIoctl with either the SIO_SET_QOS or SIO_SET_GROUP_QOS opcode.
The lpSQOS parameter specifies the FLOWSPEC structures for socket s, one for each direction, followed by any additional provider-specific parameters. If either the associated transport provider in general or the specific type of socket in particular cannot honor the quality of service request, an error will be returned as indicated in the following. The sending or receiving flow specification values will be ignored, respectively, for any unidirectional sockets. If no provider-specific parameters are specified, the buf and len members of the WSABUF structure pointed to by the lpCalleeData parameter should be set to NULL and zero, respectively. A NULL value for lpSQOS parameter indicates no application-supplied quality of service.
Reserved for future use with socket groups lpGQOS specifies the FLOWSPEC structures for the socket group (if applicable), one for each direction, followed by any additional provider-specific parameters. If no provider-specific parameters are specified, the buf and len members of the WSABUF structure pointed to by the lpCalleeData parameter should be set to NULL and zero, respectively. A NULL value for lpGQOS indicates no application-supplied group quality of service. This parameter will be ignored if s is not the creator of the socket group.
When connected sockets become closed for whatever reason, they should be discarded and recreated. It is safest to assume that when things go awry for any reason on a connected socket, the application must discard and recreate the needed sockets in order to return to a stable point.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.