Ошибка подключения сокета winsock

У коллеги на домашнем компьютере с Windows 10 стал периодически (раз в 2-3 дня) пропадать доступ в интернет (статус “Ограничено” у подключения), а при запуске мастера диагностики сетей Windows (запускается при щелчке мыши по значку с ошибкой сетевого подключения или через Параметры -> Обновление и безопасность -> Устранение неполадок -> Запустить средство устранения неполадок подключения к Интернету) появляется характерная ошибка:

На этом компьютере отсутствуют один или несколько сетевых протоколов.

В реестре отсутствуют записи для Windows Sockets, необходимые для связи по сети.

На этом компьютере отсутствуют один или несколько сетевых протоколов. В реестре отсутствуют записи для Windows Sockets, необходимые для связи по сети

One or more network protocols are missing on this computer.

Windows Sockets registry entries required for network connectivity are missing.

Коллега обычно решал проблему перезагрузкой Windows и роутера, после чего подключение в интернет работало какое-то время, но через день-два проблема повторялась. Недавно он попросил меня попробовать исправить ошибку с отсутствующими сетевыми протоколами. Вот что получилось у меня.

При такой плавающей проблеме обычно рекомендуется начать с самого простого — сбросить текущие настройки TCP/IP и Windows Sockets. Если у вас на компьютере IP адрес настроен вручную, а не через DHCP, следующие команды сбросят ваши сетевые настройки. Поэтому предварительно нужно записать текущие настройки IP адреса, маски, шлюза и DNS серверов для ваших сетевых подключений (подробнее про сброс сетевых настроек в Windows).

netsh winsock reset

netsh winsock reset

Sucessfully reset the Winsock Catalog.
You must restart the computer in order to complete the reset.

netsh interface ipv4 reset

netsh interface ipv4 reset

Resetting Compartment Forwarding, OK!
Resetting Compartment, OK!
Resetting Control Protocol, OK!
Resetting Echo Sequence Request, OK!
Resetting Global, OK!
Resetting Interface, OK!
Resetting Anycast Address, OK!
Resetting Multicast Address, OK!
Resetting Unicast Address, OK!
Resetting Neighbor, OK!
Resetting Path, OK!
Resetting Potential, OK!
Resetting Prefix Policy, OK!
Resetting Proxy Neighbor, OK!
Resetting Route, OK!
Resetting Site Prefix, OK!
Resetting Subinterface, OK!
Resetting Wakeup Pattern, OK!
Resetting Resolve Neighbor, OK!
Resetting , OK!

Данные команды сбросят настройки протокола TCP/IP для всех сетевых адаптеров и все обработчики (Winsock Layered Service Providers) к начальному, чистому состоянию. В результате вы удалите все сторонние обработчики, которые были встроены в ваш стек Winsock сторонними программами. Чаще всего в стек Winsock встраивают свои библиотеки-обработчики антивирусы, сниферы, файерволами и даже некоторые вирусы :).

После выполнения всех команду нужно перезагрузить компьютер и проверить интернет-подключение.

Если проблема не решилась, нужно через реестр удалить текущие настройки Windows Sockets.

  1. Откройте редактор реестра и перейдите к ключу HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesWinSock. Создайте резервную копию ветки реестра, экспортировав ее в reg файл (ПКМ -> Export); сохранить ветку HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesWinSock
  2. Удалите ветку (ПКМ -> Delete); удалить ветку настроек WinSock в реестре
  3. Выполните эти же действия для ветки HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesWinsock2;

После этого вам нужно вручную переустановить компоненты протокола TCP/IP.

  1. В панели управления сетевыми подключениями (ncpa.cpl) откройте свойства вашего сетевого адаптера и нажмите кнопку Install;
  2. Выберите Protocol в списке компонентов для установки (Select Network Feature Type);
  3. Затем выберите, что вы хотите установить компонент с диска и укажите путь к каталогу
    C:WindowsINF
    ; переустановка компонентов протокола TCP/IP
  4. В списоке переустанавливаемых сетевых протоколов выберите Internet Protocol version 4 (TCP/IPv4) и перезагрузите компьютер. Установить протокол Internet Protocol version 4 (TCP/IPv4) .

В моем случае при переустановке компонентов TCP/IP появилась ошибка:

Network Connections
Could not add the requested feature. The error is: This program is blocked by group policy. For more information, contact your system administrator.

Network Connections Could not add the requested feature. The error is: This program is blocked by group policy. For more information, contact your system administrator.

Чтобы исправить ошибку нужно вручную импортировать с другого компьютера с той же версий ОС и применить на проблемном ПК следующие ветки реестра: HKLMSYSTEMCurrentControlSetServicesWinsock и HKLMSYSTEMCurrentControlSetServicesWinsock2.

Можете скачать готовые файлы для чистой Windows 10 x64 LTSC по ссылкам ниже:

  • Winsock.reg
  • Winsock2.reg

После импорта reg файлов нужно перезагрузить компьютер и попробовать еще раз переустановить протокол TCP/IP (в самом крайнем случаем воспользуютесь своими ветками ресстра winsock, сохранными ранее, но лучше использовать чистые).

Теперь в свойствах вашего сетевого подключений проверьте, что он настроен на получение динамического IP адреса и настроек DNS серверов, либо укажите IP адрес и DNS сервера вручную (в моем случае после сброса статические настройки IP просто очистились ). Для домашнего компьютера можно указать использовать следующие статические адреса DNS серверов Google: 8.8.8.8 и 8.8.4.4.

проверьте настройки DNS

Здесь же нажмите на кнопку Advanced и на вкладке WINS отключите просмотр LMHOSTS и NetBIOS через TCP/IP. Эти сетевые ротоколы являются устаревшими и не нужны в современных сетях .

отключить LMHOSTS и NetBIOS через TCP/IP

После этого проблема с периодическим отключением интернета с ошибкой “отсутствуют один или несколько сетевых протоколов” в Windows 10 исчезла. Если вам и это не помогло, я бы попробовал дополнительно переустановить (обновить) драйвера ваших сетевых адаптеров. Возможно проблема еще и с ними.

Winsock — это спецификация, которая используется в Windows для определения того, как сетевые приложения взаимодействуют с сетевыми службами, такими как TCP / IP.

Это в основном определяет, как две сетевые программы будут общаться друг с другом. Например, чтобы клиент FTP работал правильно, он использует Winsock.

Однако, Winsock может испортиться на машине Windows во время удаления шпионского или рекламного ПО. Вы можете начать получать странные ошибки, связанные с ошибками Winsock или сокетов, и основные команды, такие как IPCONFIG, не будут работать правильно.

Вы также можете получить такие ошибки, как Страница не может быть отображена при попытке просматривать интернет.

Чтобы исправить ошибку Winsock, вы должны сбросить весь стек протоколов TCP / IP на вашем компьютере с Windows. Существует несколько способов решения проблемы: использование командной строки, загрузка стороннего приложения и т. Д.

Microsoft Winsock Fix

Самый простой и безопасный способ сбросить ваш стек TCP / IP — это загрузить бесплатную утилиту от Microsoft.

https://support.microsoft.com/en-us/help/299357/how-to-reset-tcp-ip-by-using-the-netshell-utility

Просто скачайте правильный файл для ваших версий Windows и пройдите мастер!

Сброс сетевого стека TCP / IP вручную

Первое, что нужно попробовать, если вышеприведенная программа не работает, это вручную сбросить сетевой стек TCP / IP. Откройте командную строку администратора, нажав кнопку Пуск и введя CMD, а затем щелкните правой кнопкой мыши командную строку и выберите Запустить от имени администратора,

Теперь введите следующую команду:

netsh int ip reset resetlog.txt

Это перезапишет два раздела реестра, которые необходимы для правильной работы TCP / IP. Это будет работать на Windows XP, Vista, 7, 8 и 10. Если это не работает, читайте ниже!

Сброс Winsock с помощью netsh

Если сброс TCP / IP не работает, попробуйте сбросить стек TCP / IP с помощью команды сброса. Сначала откройте командную строку, выбрав «Пуск», «Выполнить» и набрав CMD.

Перед вводом команды сброса следует проверить, какие LSP (многоуровневые поставщики услуг) будут затронуты. Вы можете сделать это, набрав:

netsh winsock show catalog

Команда сброса ниже удалит все LSP Winsock. Теперь введите следующую команду ниже:

netsh winsock reset catalog

Каталог Winsock будет сброшен к конфигурации по умолчанию. Если ваш LSP поврежден и вызывает проблемы с сетевым подключением, эта команда должна исправить это. Обратите внимание, что если вы запустите эту команду, вам, возможно, придется переустановить несколько программ, на которых ранее были установлены LSP.

Вы также можете ознакомиться со статьей базы знаний Майкрософт ниже, в которой подробно описываются дополнительные шаги, которые можно предпринять для устранения повреждения Winsock2 в Windows XP и Windows Vista:

Восстановление от Winsock2 повреждения в Windows

Надеемся, что один из методов, описанных выше, решил вашу проблему с сетью! Если нет, то вам, возможно, придется переустановить Windows, поскольку она может быть повреждена без возможности восстановления.

Attention Before you read this post, I highly recommend you check out my resources page for access to the tools and services I use to not only maintain my system but also fix all my computer errors, by clicking here!

Are you currently bogged down with the Winsock error? If so, you’ve come to the right place, as I intend to explain all. 

Winsock is short for Windows Socket and is an application programming interface or API that is used by developers to create applications that communicate with other computer systems through the TCP/IP protocol. Both Windows 95 and Windows NT come with a DLL file called winsock.dll, it’s this file that does the mediation between the application and the internet protocol.

The winsock.dll file is available in a variety of versions, on one side you have the Microsoft version, and on the other, you have a number of shareware and freeware versions, the Winsock API does not have an official standard, so each version may differ somewhat from the other.

What Is A Winsock Error?

A Winsock error typically occurs within the Winsock itself, which is used as the interface between windows applications and internet connectivity. Winsock’s primarily responsibility is to govern how windows applications interface with other applications over the internet.

All Windows based computers come with at least one physical port (the Ethernet port), however, there are also ports that you can’t see, called virtual ports, and it’s these ports that are used when your computer makes multiple connections to the internet from various sources. Every computer has exactly 65535 ports. At least 60% of these ports are used by applications that require access to the internet, while some ports (0 – 1024) are reserved solely for the operating system. If any application on your computer attempts to access the internet through one of these ports, it will be denied and/or result in an error. However, this very rarely happens, since the vast majority of developers are aware of which ports are accessible and which are reserved for the OS, and for those individuals that aren’t totally up to speed on which ports they can use, and which ports are reserved, they can always checkout any public index list online.

Winsock’s responsibility in all of this is to open and close these ports that applications on your computer are using to get online. If the Winsock file gets corrupted or if a resource that Winsock requires gets corrupted, then applications on your system that require internet connectivity as part of their functionality, will cease to function as they should. The Winsock error is always the result of this particular scenario, which makes it pretty easy for you to determine what the problem is. However, when it comes to fixing it, it can be rather difficult, especially if you no idea of where to start.

What Causes The Winsock Error?

The vast majority of internet connection issues are the result of corrupt Winsock settings. Because of the various programs on your computer that use Winsock, it can be rather difficult to identify which program is the root cause of the problem. The Winsock is also a primary target for malware, as hackers attempt to access your computer through the net.

The most common culprits of the Winsock error are:

  • The registry keys of the Winsock component are corrupt.
  • The drivers for the TCP/IP protocol on your system are corrupt or missing.
  • The drivers for your NIC (Network Interface Card) are corrupt or missing.
  • An application is trying to receive or transmit data through a reserved system port.

Of the main culprits highlighted above, a corrupt registry key is the most common; however, a corrupt registry key typically results in other areas of the registry being corrupt to. The manual approach to rectifying this issue is fairly comprehensive, however, I’ve taken the time to jot down the entire procedure; continue reading for more information.

However, the recommended approach to addressing this issue is to use automated software.

The majority of Winsock errors are typically the result of registry corruption. Just one simple mistake is capable of causing all kinds of heartache which in some cases, only automated tools are capable of fixing. The good thing is that, despite the difficulties in fixing the problem manually, if you use the right tool, you can fix the problem in a matter of minutes. The first tool I’ll like to recommend is Advanced System Repair Pro, and that’s because of its proficiency in repairing corrupt registries. You can find out more about this program here:

CLICK HERE TO CHECK OUT ADVANCED SYSTEM REPAIR PRO

The two other tools that I think you should try are WinSock XP Fix and WinSockFix, both of which are capable of fixing errors related to the Winsock and have the testimonials to prove it.

The solution(s) below are for ADVANCED level computer users. If you are a beginner to intermediate computer user, I highly recommend you use the

automated tool(s)

above!

Verifying Your Internet Protocols

The first thing you’re going to want to do is ensure that you have all the appropriate internet protocols present on your computer.

1. First, log into your computer with a user profile that has administrative rights.

2. Then click on Start -> Run [Windows Vista/7: Press windows key + R], type msinfo32, and click on OK.

run msinfo32

3. This will load the System Information applet, on the left pane, click on the + symbol next to Components -> Network -> Protocol.

Protocol Information

Within the Protocol, on the right pane, as you scroll down, you should have at least 10 sections labelled with the following names:

  • MSAFD Tcpip [TCP/IP]
  • RSVP UDP Service Provider
  • MSAFD NetBIOS

If on your computer its showing less than ten sections with names that differ from those listed above, then it means you have missing data that Winsock requires in order to function properly. To rectify this problem, you’re going to have to rebuild the Winsock component.

Rebuild the Winsock

One thing you should be aware of when rebuilding or resetting the Winsock, is that if you’re running Windows XP with Service Pack 2, then it will restore all Winsock settings including your third-party LSPs back to their factory defaults. LSPs are settings created by applications that use the Winsock, this means, you will have to reinstall some applications on your computer after completing this procedure.

1. First start by logging into your system with administrative rights.

2. Then click on Start -> Run, type cmd and click on OK. [Windows Vista/7: Start -> Type cmd (into the Search programs and files box) and Press CTRL + Shift + Enter, then click on Continue]

Run cmd

3. Once Command Prompt loads up, type “netsh winsock reset” and hit Enter.

Command netsh winsock reset

After you’ve run this command, you must reboot your computer in order for the changes to take effect.

Deleting the Corrupt Registry Keys

The next step is to remove the corrupt registry keys created by Winsock, so that new ones can be made in their stead.

WARNING: Editing or deleting the wrong registry entry can damage your operating system beyond repair.

1. First, log into your computer with administrative rights.

2. Then click on Start -> Run [Windows Vista/7: Press windows key + R], type regedit and click on OK.

Run registry editor

3. Once the Registry Editor loads up, navigate to the following path:

HKEY_LOCAL_MACHINESystemCurrentControlSetServices

HKEY_LOCAL_MACHINESystemCurrentControlSetServices

4. Once there, click on the + symbol next to Services to reveal all its sub keys.

Access Sub Keys

5. Then scroll down to you find the registry sub keys Winsock and Winsock2 and right click on each one and select Delete.

Remove Winsock Sub keys

Once you’ve removed both sub keys, restart your system.

Reinstall the Internet Protocol Drivers

Once you’ve removed the sub keys from your registry, you’ll want to reinstall the Internet Protocol drivers, so that connections to the internet are possible through third party applications.

1. To complete this procedure, you must first log into your computer with administrative rights.

2. Then click on Start -> Control Panel.

Open Control Panel

3. Once Control Panel loads up, double click on Network Connections.

Run Network Connections

4. From Network Connections, under LAN or High-Speed Internet, right click on Local Area Connection and select Properties.

Properties of Local Area Connection

5. This will bring up the Local Area Connection Properties applet, from here, click on Install.

Install New Protocol

6. For the Network Component Type, select Protocol and click on Add.

Add New Network Component

7. On the Select Network Protocol applet, click on Have Disk.

Select Network Protocol

8. Then type “C:Windowsinf” and click on OK.

Find Drivers from C:Windowsinf

9. Lastly, select Internet Protocol (TCP/IP) from the list and click on OK.

Add Internet Protocol (TCP/IP)

The steps above should be sufficient in rectifying any issues you have with the Winsock, however, in the event that it’s not, you should consider running system file checker.

System File Checker

The system file checker is a Windows utility tool that will scan your system for any missing or corrupt system files and replace them. In order for you to run this tool, you must have your operating system on CD.

1. First, begin by logging into your computer with administrative rights.

2. Then click on Start -> Run, type cmd and click on OK. [Windows Vista/7: Start -> Type cmd (into the Search programs and files box) and Press CTRL + Shift + Enter, then click on Continue]

Run cmd

3. Once Command Prompt loads up, type “sfc /scannow” and press Enter.

Run sfc.exe /scannow

Note: Make sure you have your OS CD in your CD/DVD Rom drive before you hit Enter.

If after following all the steps below, you’re still getting a Winsock error, then you should consider running a repair installation. For more information on how to do this manually, you can check out my post on how to speed up your system.

However, the manual option requires a certain level of expertise and also for you to have your Windows CD, which can be a problem, as most systems come with their operating system pre-installed. However, as an alternative, you can use a Windows repair tool called Reimage, which can automatically reinstall your operating system on the fly, without the requirement of a Windows CD and at no risk to your personal files.

For more information on this product, visit the following link:

CLICK HERE TO CHECK OUT REIMAGE

Are you looking for a way to repair all the errors on your computer?

Advanced System Repair Pro image

If the answer is Yes, then I highly recommend you check out Advanced System Repair Pro.

Which is the leading registry cleaner program online that is able to cure your system from a number of different ailments such as Windows Installer Errors, Runtime Errors, Malicious Software, Spyware, System Freezing, Active Malware, Blue Screen of Death Errors, Rundll Errors, Slow Erratic Computer Performance, ActiveX Errors and much more. Click here to check it out NOW!

I dont understand whats happening. If I create a socket to anywhere else other than localhost (either «localhost», «127.0.0.1» or the external ip of the machine) it works fine.
If I create a socket to an address without something listening in that port i would get a 10060 (timeout) but not a 10061 which makes sense. Why is it that I am getting connection refused when going to localhost.
I tried disabling the firewall just in case it was messing things up, but that is not it

I am doing all the WSA initialize stuff before this.

    _socketToServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(_socketToServer == -1){
    return false;
    }

   p_int = (int*)malloc(sizeof(int));
   *p_int = 1;
   if( (setsockopt(_socketToServer, SOL_SOCKET, SO_REUSEADDR, 
       (char*)p_int, sizeof(int)) == -1 )||
       (setsockopt(_socketToServer, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int,
               sizeof(int)) == -1 ) ){
        free(p_int);
        return false;
   }
   free(p_int);


   struct sockaddr_in my_addr;

   my_addr.sin_family = AF_INET ;
   my_addr.sin_port = htons(_serverPort);

   memset(&(my_addr.sin_zero), 0, 8);
   my_addr.sin_addr.s_addr = inet_addr(_serverIP);


   if( connect( _socketToServer, (struct sockaddr*)&my_addr, sizeof(my_addr)) 
        == SOCKET_ERROR ){
    DWORD error = GetLastError(); //here is where I get the 10061
    return false;
}

Any ideas?

I dont understand whats happening. If I create a socket to anywhere else other than localhost (either «localhost», «127.0.0.1» or the external ip of the machine) it works fine.
If I create a socket to an address without something listening in that port i would get a 10060 (timeout) but not a 10061 which makes sense. Why is it that I am getting connection refused when going to localhost.
I tried disabling the firewall just in case it was messing things up, but that is not it

I am doing all the WSA initialize stuff before this.

    _socketToServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(_socketToServer == -1){
    return false;
    }

   p_int = (int*)malloc(sizeof(int));
   *p_int = 1;
   if( (setsockopt(_socketToServer, SOL_SOCKET, SO_REUSEADDR, 
       (char*)p_int, sizeof(int)) == -1 )||
       (setsockopt(_socketToServer, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int,
               sizeof(int)) == -1 ) ){
        free(p_int);
        return false;
   }
   free(p_int);


   struct sockaddr_in my_addr;

   my_addr.sin_family = AF_INET ;
   my_addr.sin_port = htons(_serverPort);

   memset(&(my_addr.sin_zero), 0, 8);
   my_addr.sin_addr.s_addr = inet_addr(_serverIP);


   if( connect( _socketToServer, (struct sockaddr*)&my_addr, sizeof(my_addr)) 
        == SOCKET_ERROR ){
    DWORD error = GetLastError(); //here is where I get the 10061
    return false;
}

Any ideas?

Содержание

  • Что такое Winsock и для чего он нужен?
  • Почему полезно сбросить Netsh Winsock
  • Как перезапустить его в Windows 11 или Windows 10
  • Выводы

Имя Винсока происходит от Разъем Windows . Можно сказать, что это программный интерфейс, который используется для установления связи между сетевым программным обеспечением Windows и сетевыми службами. Он использует протокол TCP/IP, чтобы программы, которым необходим доступ к Интернету, могли подключаться.

Это в основном служит для того, чтобы программы могут подключаться к Интернету . Например, приложение для обмена сообщениями, программа для загрузки файлов в облако и т. д. Любое приложение, которое вы установили в Windows и которому для работы требуется доступ к сети, будет зависеть от Winsock.

Несмотря на то, что он входит в стандартную комплектацию Microsoft операционных системах, мы также можем найти его в других, таких как macOS. Это не что-то новое, так как оно было создано несколько десятилетий назад. Со временем он адаптировался к новым версиям системы и к потребностям программ, которые мы устанавливаем.

Можно сказать, что Винсок отвечает за прием и отправка запросов . Что он делает, так это транслирует запросы для выполнения различных задач, требующих использования протокола TCP/IP. Таким образом, это необходимый инструмент для многих функций, которые мы выполняем в повседневной жизни в Интернете. Если что-то пойдет не так, если возникнет проблема, она не сможет работать правильно, и нам придется принять определенные меры, чтобы программы, зависящие от этой функции, могли выполняться правильно.

Почему полезно сбросить Netsh Winsock

Так чем же интересно сбросить Winsock? Уинсок будет хранить важную информацию о том, как эти приложения и коммуникации будут взаимодействовать. Эта база данных может быть повреждена и перестать работать должным образом. Например, если на компьютер проник вирус, неправильная конфигурация системы, неудачное обновление и т. д. Имейте в виду, что то, что мы упомянули, также может повлиять на просмотр, хотя это не то, что напрямую влияет на эту функцию Windows.

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

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

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

Как перезапустить его в Windows 11 или Windows 10

Сброс Winsock в Windows 10 или Windows 11 — очень простой процесс. Просто выполнив ряд шагов, вы сможете сбросить этот компонент и посмотреть, устраняет ли он ошибку, возникающую при подключении при использовании некоторых приложений. Вам не придется ничего устанавливать, так как все идет с самой операционной системой.

Первое, что вам нужно сделать, это зайти в «Пуск» и выполнить поиск «Терминал», «Командная строка» или «CMD». Вы должны запустить его с правами администратора, поэтому щелкните его правой кнопкой мыши и нажмите «Запуск от имени администратора». Это необходимо для выполнения команды.

Выключить терминал Windows

После того, как вы находитесь в терминале или командной строке и открыли его с правами администратора, следующее, что вам нужно сделать, это выполнить следующую команду в открывшемся окне:

  • Netsh сброс Winsock

Reiniciar Winsock в Windows

Позже вы должны увидеть сообщение в том же окне о том, что Winsock был успешно сброшен . Это быстрый процесс, и вам не нужно ничего делать. Если вы выполнили эти шаги, вы просто увидите это сообщение, указывающее, что оно было выполнено успешно, и все.

Процесс одинаков независимо от того, используете ли вы Windows 10 или Windows 11. Вы сможете запустить команду из Терминал or Командная строка и быстро сбросить эту системную функцию.

После сброса Winsock в Windows следующее, что нужно сделать, это перезагрузить систему. Это важно каждый раз, когда вы вносите такое изменение, так как это гарантирует, что оно было сделано правильно, и позволяет избежать проблем, которые могут повлиять на производительность и ограничить удобство использования.

Выводы

Короче говоря, как вы видели, это очень легко сбросить Winsock в Windows . Это процесс, который вам придется выполнить, если вы столкнетесь с проблемами подключения, такими как сбой в работе приложений, которым необходимо подключение к Интернету, есть обрывы или они даже не могут подключиться.

Одна из причин проблем с приложения, которым нужен интернет в Windows в том, что была проблема с Winsock. Поэтому, сбросив его, мы можем снова заставить его нормально работать и снова иметь доступ к сети при использовании этих программ.

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

Windows Sockets или Winsock — это техническая спецификация или программный интерфейс, который определяет, как любая программа обрабатывает запросы ввода / вывода для Интернет-приложений, например TCP / IP в Windows. В этом руководстве мы узнаем о Winsock, о том, почему и когда вам нужно выполнить сброс, а также о том, как сбросить Winsock в Windows 10.

Что такое Winsock

Как мы уже говорили, это программный интерфейс. Windows 10 содержит DLL с именем winsock.dll, которая реализует API и координирует программы Windows и соединения TCP / IP. В настройках содержится конфигурация компьютера для подключения к Интернету.

Когда нужно сбросить Winsock

Иногда сокеты Windows или Winsock могут быть повреждены, в результате чего вы не сможете подключиться к Интернету. Ошибка может возникнуть при загрузке неизвестного файла с вредоносным сценарием. Эти сценарии могут частично блокировать Winsock, блокируя ваше интернет-соединение. Если у вас возникают проблемы с открытием веб-сайтов, это может быть связано с поврежденными настройками Winsock.

Если вы получаете какое-либо из следующих или аналогичных сообщений об ошибках, это означает, что вам необходимо сбросить Winsock:

  • Произошла ошибка при обновлении интерфейса «Интернет»: была предпринята попытка выполнить операцию с чем-то, кроме сокета.
  • Произошла ошибка при обновлении подключения по локальной сети интерфейса: запрошенный поставщик услуг не может быть загружен или инициализирован.
  • Произошла ошибка при обновлении подключения к локальной сети интерфейса: была предпринята попытка выполнить операцию с чем-то, что не является сокетом. Невозможно связаться с водителем. Код ошибки 2.
  • Операция завершилась неудачно, поскольку ни один адаптер не находится в состоянии, допустимом для этой операции.

Вот шаги, которые необходимо предпринять для сброса Winsock в Windows 10:

  1. Щелкните правой кнопкой мыши кнопку Пуск
  2. Выберите командную строку (администратор)
  3. Введите netsh winsock reset и нажмите Enter.
  4. Для создания файла журнала используйте вместо этого netsh winsock reset c: winsocklog.txt.
  5. Перезагрузите компьютер.

Прежде чем продолжить и сбросить Winsock, не забудьте сначала создать точку восстановления системы.

Затем откройте командную строку от имени администратора, введите следующую команду и нажмите Enter.

сброс WinSock Netsh

Как администратор, вы также можете создать файл журнала изменений.

Чтобы добавить путь к файлу журнала к указанной выше команде:

netsh winsock сбросить c: winsocklog.txt

Подождите, пока командная строка выполнит сброс. Теперь вам придется перезагрузить компьютер, чтобы увидеть эффекты.

Что происходит при сбросе Winsock

Когда вы выполняете команду, она исправляет все повреждения, которые произошли с файлом DLL. Таким образом, нет никакого исправления, кроме как заменить его новой копией Winsock и вернуть его к настройкам по умолчанию.

СОВЕТ: Наша портативная бесплатная программа FixWin позволяет сбросить этот и большинство других параметров и функций Windows одним щелчком мыши.

ПРИМЕЧАНИЕ. Вот пакетный файл для одновременного освобождения TCP / IP, очистки DNS, сброса Winsock, сброса прокси.

Связанные чтения:

  1. Как очистить кеш DNS
  2. Как сбросить TCP / IP
  3. Как сбросить настройки прокси-сервера WinHTTP.

.

Сброс Winsock

Иногда эксперименты с настройками сетевых карт, либо вирусы, черви и трояны, или же слишком агрессивные антивирусы повреждают настройки Winsock, что приводит к неадекватной работе сетевых компонентов в системе

Проблема: не работает сеть.

Возможные симптомы:
— Компьютер не получает ip-адрес автоматически. При ручных настройках сеть работает. Служба DHCP-клиент при этом включена.
— Есть пинг по адресам, но нет по именам. Службы DNS-клиент при этом включена.
— Компьютер получает адрес из пространства APIPA (169.254.*.*) практически мгновенно после включения сети, а не после ожидания и таймаута.
— При попытке пинга из командной строки определенного IP-адреса, в ответном сообщении системы после слов «Обмен пакетами с» идут различные непечатные символы, такие как треугольнички, сердечки и т.д.
— Компьютер получает настройки сети не полностью, например получает только адрес шлюза.
— Стартуют и останавливаются большинство сетевых служб.
— Исчезли все созданные сетевые подключения.

Причина:
Такое поведение наблюдается при повреждении разделов реестра, в которых хранится конфигурация Winsock. Что же такое Winsock? Если сказать в «двух словах», то Winsock это интерфейс, который упрощает разработку сетевых приложений под Windows. Всё что нам нужно знать, это то что Winsock представляет собой интерфейс между приложением и транспортным протоколом, выполняющим передачу данных.При взаимодействии клиент — сервер в сети каждого участника взаимодействия можно рассматривать как конечную точку. Сокет это вроде как и есть эта конечная точка. В приложении вы определяете сокет.

Решение:
Нажмите Пуск, в поле Начать поиск введите

cmd

, щелкните правой кнопкой мыши файл

cmd.exe

и выберите команду

Запуск от имени администратора

, а затем нажмите кнопку Продолжить.
Введите в командной строке команду

netsh winsock reset

и нажмите клавишу Enter. После выполнения команды перезагрузите компьютер.

Для чего нужна команда «netsh winsock reset»?

Кликните здесь для просмотра всего текста

-для предотвращения атак отказа в обслуживании и отправления пакетов от чужого имени ограничена возможность передачи данных с помощью сокетов;
-ограничение частоты создания сетевых подключений. Т.е. соединений может быть сколько угодно, но установить множество подключений одновременно уже не получится, т.к. при достижении максимального числа разрешенных все последующие ставятся в очередь и выполняются с заданной частотой (что в равной степени относится и к сканированию портов).
-это изменение позволяет замедлить скорость распространения вирусов и червей, благодаря чему снижается риск массовых эпидемий, и антивирусные компании выигрывают немного времени на изготовление «противоядия».

Реализация восстановления Winsock после удаления LSP

Winsock используется для обработки данных, передаваемых по протоколу TCP/IP, в процессе которой информация последовательно проходит все установленные на компьютере обработчики этих данных — LSP (Layered Service Provider). Если один из них будет некорректно удален, то цепочка обработки нарушается, и работа по протоколу TCP/IP становится невозможной. Такие ситуации нередко случались, когда в Winsock для перехвата какой-либо информации внедрялось вредоносное приложение. При удалении его антивирусом пользователь лишался сети Интернет, либо был вынужден восстанавливать удаленные вредоносные компоненты. Благодаря автоматическому восстановлению цепочки Winsock необходимость в корректном удалении LSP во многих случаях наконец-то отпала.

Вместе с этим стали доступны две новые команды Netsh:

netsh winsock show catalog

— отображение списка установленных на компьютере LSP Winsock.

netsh winsock reset catalog

— сброс настроек и восстановление первоначальной конфигурации LSP Winsock

Переустановка протокола tcp/ip

При установке в составе какой-нибудь сборки Windows иногда может некорректно установиться сетевой протокол TCP/IP. В этом случае нужно его переустановить, и по-другому просто никак.

Как это сделать:

Кликните здесь для просмотра всего текста

1. Запустить regedit и удалить 2 ключа в реестре:
HKEY_LOCAL_MACHINESystemCurrentControlSetServic esWinsock
HKEY_LOCAL_MACHINESystemCurrentControlSetServic esWinSock2

2. В файле Nettcpip.inf (находится в папке windowsinf) найти раздел [MS_TCPIP.PrimaryInstall] и в записи Characteristics = 0xa0 заменить 0xa0 на 0x80.

3. Зайти в Панели управления в Сетевые подключения, правой кнопкой мыши щелкнуть значок Подключение по локальной сети и выбрать Свойства.

4. Открыть вкладку Общие и последовательно щелкнуть Установить, Протокол и Добавить.

5. В окне Выбор сетевых протоколов щелкнуть Установить с диска.

6. В окне Копировать файлы с диска ввести C:Windowsinf и нажмите кнопку ОК.

7. Выделить пункт Протокол Интернета (TCP/IP) и нажмите кнопку ОК.

8. Вернуться на экран Подключение по локальной сети, но кнопка Удалить теперь активна.

9. Теперь можно удалить Протокол Интернета (TCP/IP).

10. Перезагрузить компьютер.

11. Зайти опять в Сетевые подключения и установить Протокол Интернета (TCP/IP) заново, используя кнопку Установить с диска и путь c:windowsinf.

12. Перезагрузить компьютер.

Attention Before you read this post, I highly recommend you check out my resources page for access to the tools and services I use to not only maintain my system but also fix all my computer errors, by clicking here!

Are you currently bogged down with the Winsock error? If so, you’ve come to the right place, as I intend to explain all. 

Winsock is short for Windows Socket and is an application programming interface or API that is used by developers to create applications that communicate with other computer systems through the TCP/IP protocol. Both Windows 95 and Windows NT come with a DLL file called winsock.dll, it’s this file that does the mediation between the application and the internet protocol.

The winsock.dll file is available in a variety of versions, on one side you have the Microsoft version, and on the other, you have a number of shareware and freeware versions, the Winsock API does not have an official standard, so each version may differ somewhat from the other.

What Is A Winsock Error?

A Winsock error typically occurs within the Winsock itself, which is used as the interface between windows applications and internet connectivity. Winsock’s primarily responsibility is to govern how windows applications interface with other applications over the internet.

All Windows based computers come with at least one physical port (the Ethernet port), however, there are also ports that you can’t see, called virtual ports, and it’s these ports that are used when your computer makes multiple connections to the internet from various sources. Every computer has exactly 65535 ports. At least 60% of these ports are used by applications that require access to the internet, while some ports (0 – 1024) are reserved solely for the operating system. If any application on your computer attempts to access the internet through one of these ports, it will be denied and/or result in an error. However, this very rarely happens, since the vast majority of developers are aware of which ports are accessible and which are reserved for the OS, and for those individuals that aren’t totally up to speed on which ports they can use, and which ports are reserved, they can always checkout any public index list online.

Winsock’s responsibility in all of this is to open and close these ports that applications on your computer are using to get online. If the Winsock file gets corrupted or if a resource that Winsock requires gets corrupted, then applications on your system that require internet connectivity as part of their functionality, will cease to function as they should. The Winsock error is always the result of this particular scenario, which makes it pretty easy for you to determine what the problem is. However, when it comes to fixing it, it can be rather difficult, especially if you no idea of where to start.

What Causes The Winsock Error?

The vast majority of internet connection issues are the result of corrupt Winsock settings. Because of the various programs on your computer that use Winsock, it can be rather difficult to identify which program is the root cause of the problem. The Winsock is also a primary target for malware, as hackers attempt to access your computer through the net.

The most common culprits of the Winsock error are:

  • The registry keys of the Winsock component are corrupt.
  • The drivers for the TCP/IP protocol on your system are corrupt or missing.
  • The drivers for your NIC (Network Interface Card) are corrupt or missing.
  • An application is trying to receive or transmit data through a reserved system port.

Of the main culprits highlighted above, a corrupt registry key is the most common; however, a corrupt registry key typically results in other areas of the registry being corrupt to. The manual approach to rectifying this issue is fairly comprehensive, however, I’ve taken the time to jot down the entire procedure; continue reading for more information.

However, the recommended approach to addressing this issue is to use automated software.

The majority of Winsock errors are typically the result of registry corruption. Just one simple mistake is capable of causing all kinds of heartache which in some cases, only automated tools are capable of fixing. The good thing is that, despite the difficulties in fixing the problem manually, if you use the right tool, you can fix the problem in a matter of minutes. The first tool I’ll like to recommend is Advanced System Repair Pro, and that’s because of its proficiency in repairing corrupt registries. You can find out more about this program here:

CLICK HERE TO CHECK OUT ADVANCED SYSTEM REPAIR PRO

The two other tools that I think you should try are WinSock XP Fix and WinSockFix, both of which are capable of fixing errors related to the Winsock and have the testimonials to prove it.

The solution(s) below are for ADVANCED level computer users. If you are a beginner to intermediate computer user, I highly recommend you use the automated tool(s) above!

Verifying Your Internet Protocols

The first thing you’re going to want to do is ensure that you have all the appropriate internet protocols present on your computer.

1. First, log into your computer with a user profile that has administrative rights.

2. Then click on Start -> Run [Windows Vista/7: Press windows key + R], type msinfo32, and click on OK.

run msinfo32

3. This will load the System Information applet, on the left pane, click on the + symbol next to Components -> Network -> Protocol.

Protocol Information

Within the Protocol, on the right pane, as you scroll down, you should have at least 10 sections labelled with the following names:

  • MSAFD Tcpip [TCP/IP]
  • RSVP UDP Service Provider
  • MSAFD NetBIOS

If on your computer its showing less than ten sections with names that differ from those listed above, then it means you have missing data that Winsock requires in order to function properly. To rectify this problem, you’re going to have to rebuild the Winsock component.

Rebuild the Winsock

One thing you should be aware of when rebuilding or resetting the Winsock, is that if you’re running Windows XP with Service Pack 2, then it will restore all Winsock settings including your third-party LSPs back to their factory defaults. LSPs are settings created by applications that use the Winsock, this means, you will have to reinstall some applications on your computer after completing this procedure.

1. First start by logging into your system with administrative rights.

2. Then click on Start -> Run, type cmd and click on OK. [Windows Vista/7: Start -> Type cmd (into the Search programs and files box) and Press CTRL + Shift + Enter, then click on Continue]

Run cmd

3. Once Command Prompt loads up, type “netsh winsock reset” and hit Enter.

Command netsh winsock reset

After you’ve run this command, you must reboot your computer in order for the changes to take effect.

Deleting the Corrupt Registry Keys

The next step is to remove the corrupt registry keys created by Winsock, so that new ones can be made in their stead.

WARNING: Editing or deleting the wrong registry entry can damage your operating system beyond repair.

1. First, log into your computer with administrative rights.

2. Then click on Start -> Run [Windows Vista/7: Press windows key + R], type regedit and click on OK.

Run registry editor

3. Once the Registry Editor loads up, navigate to the following path:

HKEY_LOCAL_MACHINESystemCurrentControlSetServices

HKEY_LOCAL_MACHINESystemCurrentControlSetServices

4. Once there, click on the + symbol next to Services to reveal all its sub keys.

Access Sub Keys

5. Then scroll down to you find the registry sub keys Winsock and Winsock2 and right click on each one and select Delete.

Remove Winsock Sub keys

Once you’ve removed both sub keys, restart your system.

Reinstall the Internet Protocol Drivers

Once you’ve removed the sub keys from your registry, you’ll want to reinstall the Internet Protocol drivers, so that connections to the internet are possible through third party applications.

1. To complete this procedure, you must first log into your computer with administrative rights.

2. Then click on Start -> Control Panel.

Open Control Panel

3. Once Control Panel loads up, double click on Network Connections.

Run Network Connections

4. From Network Connections, under LAN or High-Speed Internet, right click on Local Area Connection and select Properties.

Properties of Local Area Connection

5. This will bring up the Local Area Connection Properties applet, from here, click on Install.

Install New Protocol

6. For the Network Component Type, select Protocol and click on Add.

Add New Network Component

7. On the Select Network Protocol applet, click on Have Disk.

Select Network Protocol

8. Then type “C:Windowsinf” and click on OK.

Find Drivers from C:Windowsinf

9. Lastly, select Internet Protocol (TCP/IP) from the list and click on OK.

Add Internet Protocol (TCP/IP)

The steps above should be sufficient in rectifying any issues you have with the Winsock, however, in the event that it’s not, you should consider running system file checker.

System File Checker

The system file checker is a Windows utility tool that will scan your system for any missing or corrupt system files and replace them. In order for you to run this tool, you must have your operating system on CD.

1. First, begin by logging into your computer with administrative rights.

2. Then click on Start -> Run, type cmd and click on OK. [Windows Vista/7: Start -> Type cmd (into the Search programs and files box) and Press CTRL + Shift + Enter, then click on Continue]

Run cmd

3. Once Command Prompt loads up, type “sfc /scannow” and press Enter.

Run sfc.exe /scannow

Note: Make sure you have your OS CD in your CD/DVD Rom drive before you hit Enter.

If after following all the steps below, you’re still getting a Winsock error, then you should consider running a repair installation. For more information on how to do this manually, you can check out my post on how to speed up your system.

However, the manual option requires a certain level of expertise and also for you to have your Windows CD, which can be a problem, as most systems come with their operating system pre-installed. However, as an alternative, you can use a Windows repair tool called Reimage, which can automatically reinstall your operating system on the fly, without the requirement of a Windows CD and at no risk to your personal files.

For more information on this product, visit the following link:

CLICK HERE TO CHECK OUT REIMAGE

Are you looking for a way to repair all the errors on your computer?

Advanced System Repair Pro image

If the answer is Yes, then I highly recommend you check out Advanced System Repair Pro.

Which is the leading registry cleaner program online that is able to cure your system from a number of different ailments such as Windows Installer Errors, Runtime Errors, Malicious Software, Spyware, System Freezing, Active Malware, Blue Screen of Death Errors, Rundll Errors, Slow Erratic Computer Performance, ActiveX Errors and much more. Click here to check it out NOW!

У коллеги на домашнем компьютере с Windows 10 стал периодически (раз в 2-3 дня) пропадать доступ в интернет (статус “Ограничено” у подключения), а при запуске мастера диагностики сетей Windows (запускается при щелчке мыши по значку с ошибкой сетевого подключения или через Параметры -> Обновление и безопасность -> Устранение неполадок -> Запустить средство устранения неполадок подключения к Интернету) появляется характерная ошибка:

На этом компьютере отсутствуют один или несколько сетевых протоколов.

В реестре отсутствуют записи для Windows Sockets, необходимые для связи по сети.

На этом компьютере отсутствуют один или несколько сетевых протоколов. В реестре отсутствуют записи для Windows Sockets, необходимые для связи по сети

One or more network protocols are missing on this computer.

Windows Sockets registry entries required for network connectivity are missing.

Коллега обычно решал проблему перезагрузкой Windows и роутера, после чего подключение в интернет работало какое-то время, но через день-два проблема повторялась. Недавно он попросил меня попробовать исправить ошибку с отсутствующими сетевыми протоколами. Вот что получилось у меня.

При такой плавающей проблеме обычно рекомендуется начать с самого простого — сбросить текущие настройки TCP/IP и Windows Sockets. Если у вас на компьютере IP адрес настроен вручную, а не через DHCP, следующие команды сбросят ваши сетевые настройки. Поэтому предварительно нужно записать текущие настройки IP адреса, маски, шлюза и DNS серверов для ваших сетевых подключений (подробнее про сброс сетевых настроек в Windows).

netsh winsock reset

netsh winsock reset

Sucessfully reset the Winsock Catalog.
You must restart the computer in order to complete the reset.

netsh interface ipv4 reset

netsh interface ipv4 reset

Resetting Compartment Forwarding, OK!
Resetting Compartment, OK!
Resetting Control Protocol, OK!
Resetting Echo Sequence Request, OK!
Resetting Global, OK!
Resetting Interface, OK!
Resetting Anycast Address, OK!
Resetting Multicast Address, OK!
Resetting Unicast Address, OK!
Resetting Neighbor, OK!
Resetting Path, OK!
Resetting Potential, OK!
Resetting Prefix Policy, OK!
Resetting Proxy Neighbor, OK!
Resetting Route, OK!
Resetting Site Prefix, OK!
Resetting Subinterface, OK!
Resetting Wakeup Pattern, OK!
 Resetting Resolve Neighbor, OK!
Resetting , OK!

Данные команды сбросят настройки протокола TCP/IP для всех сетевых адаптеров и все обработчики (Winsock Layered Service Providers) к начальному, чистому состоянию. В результате вы удалите все сторонние обработчики, которые были встроены в ваш стек Winsock сторонними программами. Чаще всего в стек Winsock встраивают свои библиотеки-обработчики антивирусы, сниферы, файерволами и даже некоторые вирусы :).

После выполнения всех команду нужно перезагрузить компьютер и проверить интернет-подключение.

Если проблема не решилась, нужно через реестр удалить текущие настройки Windows Sockets.

  1. Откройте редактор реестра и перейдите к ключу HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesWinSock. Создайте резервную копию ветки реестра, экспортировав ее в reg файл (ПКМ -> Export); сохранить ветку HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesWinSock
  2. Удалите ветку (ПКМ -> Delete); удалить ветку настроек WinSock в реестре
  3. Выполните эти же действия для ветки HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesWinsock2;

После этого вам нужно вручную переустановить компоненты протокола TCP/IP.

  1. В панели управления сетевыми подключениями (ncpa.cpl) откройте свойства вашего сетевого адаптера и нажмите кнопку Install;
  2. Выберите Protocol в списке компонентов для установки (Select Network Feature Type);
  3. Затем выберите, что вы хотите установить компонент с диска и укажите путь к каталогу
    C:WindowsINF
    ; переустановка компонентов протокола TCP/IP
  4. В списоке переустанавливаемых сетевых протоколов выберите Internet Protocol version 4 (TCP/IPv4) и перезагрузите компьютер. Установить протокол Internet Protocol version 4 (TCP/IPv4) .

В моем случае при переустановке компонентов TCP/IP появилась ошибка:

Network Connections
Could not add the requested feature. The error is: This program is blocked by group policy. For more information, contact your system administrator.

Network Connections Could not add the requested feature. The error is: This program is blocked by group policy. For more information, contact your system administrator.

Чтобы исправить ошибку нужно вручную импортировать с другого компьютера с той же версий ОС и применить на проблемном ПК следующие ветки реестра: HKLMSYSTEMCurrentControlSetServicesWinsock и HKLMSYSTEMCurrentControlSetServicesWinsock2.

Можете скачать готовые файлы для чистой Windows 10 x64 LTSC по ссылкам ниже:

  • Winsock.reg
  • Winsock2.reg

После импорта reg файлов нужно перезагрузить компьютер и попробовать еще раз переустановить протокол TCP/IP (в самом крайнем случаем воспользуютесь своими ветками ресстра winsock, сохранными ранее, но лучше использовать чистые).

Теперь в свойствах вашего сетевого подключений проверьте, что он настроен на получение динамического IP адреса и настроек DNS серверов, либо укажите IP адрес и DNS сервера вручную (в моем случае после сброса статические настройки IP просто очистились ). Для домашнего компьютера можно указать использовать следующие статические адреса DNS серверов Google: 8.8.8.8 и 8.8.4.4.

проверьте настройки DNS

Здесь же нажмите на кнопку Advanced и на вкладке WINS отключите просмотр LMHOSTS и NetBIOS через TCP/IP. Эти сетевые ротоколы являются устаревшими и не нужны в современных сетях .

отключить LMHOSTS и NetBIOS через TCP/IP

После этого проблема с периодическим отключением интернета с ошибкой “отсутствуют один или несколько сетевых протоколов” в Windows 10 исчезла. Если вам и это не помогло, я бы попробовал дополнительно переустановить (обновить) драйвера ваших сетевых адаптеров. Возможно проблема еще и с ними.

description ms.assetid title ms.topic ms.date

Windows Sockets (Winsock) error codes returned by the WSAGetLastError function.

50b924f3-2c88-443b-8a90-4293fe5c3048

Windows Sockets Error Codes (Winsock2.h)

reference

05/31/2018

Windows Sockets Error Codes

Most Windows Sockets 2 functions do not return the specific cause of an error when the function returns. For information, see the Handling Winsock Errors topic.

The WSAGetLastError function returns the last error that occurred for the calling thread. When a particular Windows Sockets function indicates an error has occurred, this function should be called immediately to retrieve the extended error code for the failing function call. These error codes and a short text description associated with an error code are defined in the Winerror.h header file. The FormatMessage function can be used to obtain the message string for the returned error.

For information on how to handle error codes when porting socket applications to Winsock, see Error Codes — errno, h_errno and WSAGetLastError.

The following list describes the possible error codes returned by the WSAGetLastError function. Errors are listed in numerical order with the error macro name. Some error codes defined in the Winsock2.h header file are not returned from any function.

Return code/value Description

WSA_INVALID_HANDLE
6
Specified event object handle is invalid.
An application attempts to use an event object, but the specified handle is not valid.

WSA_NOT_ENOUGH_MEMORY
8
Insufficient memory available.
An application used a Windows Sockets function that directly maps to a Windows function. The Windows function is indicating a lack of required memory resources.

WSA_INVALID_PARAMETER
87
One or more parameters are invalid.
An application used a Windows Sockets function which directly maps to a Windows function. The Windows function is indicating a problem with one or more parameters.

WSA_OPERATION_ABORTED
995
Overlapped operation aborted.
An overlapped operation was canceled due to the closure of the socket, or the execution of the SIO_FLUSH command in WSAIoctl.

WSA_IO_INCOMPLETE
996
Overlapped I/O event object not in signaled state.
The application has tried to determine the status of an overlapped operation which is not yet completed. Applications that use WSAGetOverlappedResult (with the fWait flag set to FALSE) in a polling mode to determine when an overlapped operation has completed, get this error code until the operation is complete.

WSA_IO_PENDING
997
Overlapped operations will complete later.

The application has initiated an overlapped operation that cannot be completed immediately. A completion indication will be given later when the operation has been completed.

WSAEINTR
10004
Interrupted function call.
A blocking operation was interrupted by a call to WSACancelBlockingCall.

WSAEBADF
10009
File handle is not valid.
The file handle supplied is not valid.

WSAEACCES
10013
Permission denied.
An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST).
Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later), another application, service, or kernel mode driver is bound to the same address with exclusive access. Such exclusive access is a new feature of Windows NT 4.0 with SP4 and later, and is implemented by using the SO_EXCLUSIVEADDRUSE option.

WSAEFAULT
10014
Bad address.
The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).

WSAEINVAL
10022
Invalid argument.
Some invalid argument was supplied (for example, specifying an invalid level to the setsockopt function). In some instances, it also refers to the current state of the socket—for instance, calling accept on a socket that is not listening.

WSAEMFILE
10024
Too many open files.
Too many open sockets. Each implementation may have a maximum number of socket handles available, either globally, per process, or per thread.

WSAEWOULDBLOCK
10035
Resource temporarily unavailable.
This error is returned from operations on nonblocking sockets that cannot be completed immediately, for example recv when no data is queued to be read from the socket. It is a nonfatal error, and the operation should be retried later. It is normal for WSAEWOULDBLOCK to be reported as the result from calling connect on a nonblocking SOCK_STREAM socket, since some time must elapse for the connection to be established.

WSAEINPROGRESS
10036
Operation now in progress.
A blocking operation is currently executing. Windows Sockets only allows a single blocking operation—per- task or thread—to be outstanding, and if any other function call is made (whether or not it references that or any other socket) the function fails with the WSAEINPROGRESS error.

WSAEALREADY
10037
Operation already in progress.
An operation was attempted on a nonblocking socket with an operation already in progress—that is, calling connect a second time on a nonblocking socket that is already connecting, or canceling an asynchronous request (WSAAsyncGetXbyY) that has already been canceled or completed.

WSAENOTSOCK
10038
Socket operation on nonsocket.
An operation was attempted on something that is not a socket. Either the socket handle parameter did not reference a valid socket, or for select, a member of an fd_set was not valid.

WSAEDESTADDRREQ
10039
Destination address required.
A required address was omitted from an operation on a socket. For example, this error is returned if sendto is called with the remote address of ADDR_ANY.

WSAEMSGSIZE
10040
Message too long.
A message sent on a datagram socket was larger than the internal message buffer or some other network limit, or the buffer used to receive a datagram was smaller than the datagram itself.

WSAEPROTOTYPE
10041
Protocol wrong type for socket.
A protocol was specified in the socket function call that does not support the semantics of the socket type requested. For example, the ARPA Internet UDP protocol cannot be specified with a socket type of SOCK_STREAM.

WSAENOPROTOOPT
10042
Bad protocol option.
An unknown, invalid or unsupported option or level was specified in a getsockopt or setsockopt call.

WSAEPROTONOSUPPORT
10043
Protocol not supported.
The requested protocol has not been configured into the system, or no implementation for it exists. For example, a socket call requests a SOCK_DGRAM socket, but specifies a stream protocol.

WSAESOCKTNOSUPPORT
10044
Socket type not supported.
The support for the specified socket type does not exist in this address family. For example, the optional type SOCK_RAW might be selected in a socket call, and the implementation does not support SOCK_RAW sockets at all.

WSAEOPNOTSUPP
10045
Operation not supported.
The attempted operation is not supported for the type of object referenced. Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.

WSAEPFNOSUPPORT
10046
Protocol family not supported.
The protocol family has not been configured into the system or no implementation for it exists. This message has a slightly different meaning from WSAEAFNOSUPPORT. However, it is interchangeable in most cases, and all Windows Sockets functions that return one of these messages also specify WSAEAFNOSUPPORT.

WSAEAFNOSUPPORT
10047
Address family not supported by protocol family.
An address incompatible with the requested protocol was used. All sockets are created with an associated address family (that is, AF_INET for Internet Protocols) and a generic protocol type (that is, SOCK_STREAM). This error is returned if an incorrect protocol is explicitly requested in the socket call, or if an address of the wrong family is used for a socket, for example, in sendto.

WSAEADDRINUSE
10048
Address already in use.
Typically, only one usage of each socket address (protocol/IP address/port) is permitted. This error occurs if an application attempts to bind a socket to an IP address/port that has already been used for an existing socket, or a socket that was not closed properly, or one that is still in the process of closing. For server applications that need to bind multiple sockets to the same port number, consider using setsockopt (SO_REUSEADDR). Client applications usually need not call bind at all—connect chooses an unused port automatically. When bind is called with a wildcard address (involving ADDR_ANY), a WSAEADDRINUSE error could be delayed until the specific address is committed. This could happen with a call to another function later, including connect, listen, WSAConnect, or WSAJoinLeaf.

WSAEADDRNOTAVAIL
10049
Cannot assign requested address.
The requested address is not valid in its context. This normally results from an attempt to bind to an address that is not valid for the local computer. This can also result from connect, sendto, WSAConnect, WSAJoinLeaf, or WSASendTo when the remote address or port is not valid for a remote computer (for example, address or port 0).

WSAENETDOWN
10050
Network is down.
A socket operation encountered a dead network. This could indicate a serious failure of the network system (that is, the protocol stack that the Windows Sockets DLL runs over), the network interface, or the local network itself.

WSAENETUNREACH
10051
Network is unreachable.
A socket operation was attempted to an unreachable network. This usually means the local software knows no route to reach the remote host.

WSAENETRESET
10052
Network dropped connection on reset.
The connection has been broken due to keep-alive activity detecting a failure while the operation was in progress. It can also be returned by setsockopt if an attempt is made to set SO_KEEPALIVE on a connection that has already failed.

WSAECONNABORTED
10053
Software caused connection abort.
An established connection was aborted by the software in your host computer, possibly due to a data transmission time-out or protocol error.

WSAECONNRESET
10054
Connection reset by peer.
An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket). This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.

WSAENOBUFS
10055
No buffer space available.
An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.

WSAEISCONN
10056
Socket is already connected.
A connect request was made on an already-connected socket. Some implementations also return this error if sendto is called on a connected SOCK_DGRAM socket (for SOCK_STREAM sockets, the to parameter in sendto is ignored) although other implementations treat this as a legal occurrence.

WSAENOTCONN
10057
Socket is not connected.
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using sendto) no address was supplied. Any other type of operation might also return this error—for example, setsockopt setting SO_KEEPALIVE if the connection has been reset.

WSAESHUTDOWN
10058
Cannot send after socket shutdown.
A request to send or receive data was disallowed because the socket had already been shut down in that direction with a previous shutdown call. By calling shutdown a partial close of a socket is requested, which is a signal that sending or receiving, or both have been discontinued.

WSAETOOMANYREFS
10059
Too many references.
Too many references to some kernel object.

WSAETIMEDOUT
10060
Connection timed out.
A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond.

WSAECONNREFUSED
10061
Connection refused.
No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running.

WSAELOOP
10062
Cannot translate name.
Cannot translate a name.

WSAENAMETOOLONG
10063
Name too long.
A name component or a name was too long.

WSAEHOSTDOWN
10064
Host is down.
A socket operation failed because the destination host is down. A socket operation encountered a dead host. Networking activity on the local host has not been initiated. These conditions are more likely to be indicated by the error WSAETIMEDOUT.

WSAEHOSTUNREACH
10065
No route to host.
A socket operation was attempted to an unreachable host. See WSAENETUNREACH.

WSAENOTEMPTY
10066
Directory not empty.
Cannot remove a directory that is not empty.

WSAEPROCLIM
10067
Too many processes.
A Windows Sockets implementation may have a limit on the number of applications that can use it simultaneously. WSAStartup may fail with this error if the limit has been reached.

WSAEUSERS
10068
User quota exceeded.
Ran out of user quota.

WSAEDQUOT
10069
Disk quota exceeded.
Ran out of disk quota.

WSAESTALE
10070
Stale file handle reference.
The file handle reference is no longer available.

WSAEREMOTE
10071
Item is remote.
The item is not available locally.

WSASYSNOTREADY
10091
Network subsystem is unavailable.
This error is returned by WSAStartup if the Windows Sockets implementation cannot function at this time because the underlying system it uses to provide network services is currently unavailable. Users should check:
  • That the appropriate Windows Sockets DLL file is in the current path.
  • That they are not trying to use more than one Windows Sockets implementation simultaneously. If there is more than one Winsock DLL on your system, be sure the first one in the path is appropriate for the network subsystem currently loaded.
  • The Windows Sockets implementation documentation to be sure all necessary components are currently installed and configured correctly.

WSAVERNOTSUPPORTED
10092
Winsock.dll version out of range.
The current Windows Sockets implementation does not support the Windows Sockets specification version requested by the application. Check that no old Windows Sockets DLL files are being accessed.

WSANOTINITIALISED
10093
Successful WSAStartup not yet performed.
Either the application has not called WSAStartup or WSAStartup failed. The application may be accessing a socket that the current active task does not own (that is, trying to share a socket between tasks), or WSACleanup has been called too many times.

WSAEDISCON
10101
Graceful shutdown in progress.
Returned by WSARecv and WSARecvFrom to indicate that the remote party has initiated a graceful shutdown sequence.

WSAENOMORE
10102
No more results.
No more results can be returned by the WSALookupServiceNext function.

WSAECANCELLED
10103
Call has been canceled.
A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.

WSAEINVALIDPROCTABLE
10104
Procedure call table is invalid.
The service provider procedure call table is invalid. A service provider returned a bogus procedure table to Ws2_32.dll. This is usually caused by one or more of the function pointers being NULL.

WSAEINVALIDPROVIDER
10105
Service provider is invalid.
The requested service provider is invalid. This error is returned by the WSCGetProviderInfo and WSCGetProviderInfo32 functions if the protocol entry specified could not be found. This error is also returned if the service provider returned a version number other than 2.0.

WSAEPROVIDERFAILEDINIT
10106
Service provider failed to initialize.
The requested service provider could not be loaded or initialized. This error is returned if either a service provider’s DLL could not be loaded (LoadLibrary failed) or the provider’s WSPStartup or NSPStartup function failed.

WSASYSCALLFAILURE
10107
System call failure.
A system call that should never fail has failed. This is a generic error code, returned under various conditions.
Returned when a system call that should never fail does fail. For example, if a call to WaitForMultipleEvents fails or one of the registry functions fails trying to manipulate the protocol/namespace catalogs.
Returned when a provider does not return SUCCESS and does not provide an extended error code. Can indicate a service provider implementation error.

WSASERVICE_NOT_FOUND
10108
Service not found.
No such service is known. The service cannot be found in the specified name space.

WSATYPE_NOT_FOUND
10109
Class type not found.
The specified class was not found.

WSA_E_NO_MORE
10110
No more results.
No more results can be returned by the WSALookupServiceNext function.

WSA_E_CANCELLED
10111
Call was canceled.
A call to the WSALookupServiceEnd function was made while this call was still processing. The call has been canceled.

WSAEREFUSED
10112
Database query was refused.
A database query failed because it was actively refused.

WSAHOST_NOT_FOUND
11001
Host not found.
No such host is known. The name is not an official host name or alias, or it cannot be found in the database(s) being queried. This error may also be returned for protocol and service queries, and means that the specified name could not be found in the relevant database.

WSATRY_AGAIN
11002
Nonauthoritative host not found.
This is usually a temporary error during host name resolution and means that the local server did not receive a response from an authoritative server. A retry at some time later may be successful.

WSANO_RECOVERY
11003
This is a nonrecoverable error.
This indicates that some sort of nonrecoverable error occurred during a database lookup. This may be because the database files (for example, BSD-compatible HOSTS, SERVICES, or PROTOCOLS files) could not be found, or a DNS request was returned by the server with a severe error.

WSANO_DATA
11004
Valid name, no data record of requested type.
The requested name is valid and was found in the database, but it does not have the correct associated data being resolved for. The usual example for this is a host name-to-address translation attempt (using gethostbyname or WSAAsyncGetHostByName) which uses the DNS (Domain Name Server). An MX record is returned but no A record—indicating the host itself exists, but is not directly reachable.

WSA_QOS_RECEIVERS
11005
QoS receivers.
At least one QoS reserve has arrived.

WSA_QOS_SENDERS
11006
QoS senders.
At least one QoS send path has arrived.

WSA_QOS_NO_SENDERS
11007
No QoS senders.
There are no QoS senders.

WSA_QOS_NO_RECEIVERS
11008
QoS no receivers.
There are no QoS receivers.

WSA_QOS_REQUEST_CONFIRMED
11009
QoS request confirmed.
The QoS reserve request has been confirmed.

WSA_QOS_ADMISSION_FAILURE
11010
QoS admission error.
A QoS error occurred due to lack of resources.

WSA_QOS_POLICY_FAILURE
11011
QoS policy failure.
The QoS request was rejected because the policy system couldn’t allocate the requested resource within the existing policy.

WSA_QOS_BAD_STYLE
11012
QoS bad style.
An unknown or conflicting QoS style was encountered.

WSA_QOS_BAD_OBJECT
11013
QoS bad object.
A problem was encountered with some part of the filterspec or the provider-specific buffer in general.

WSA_QOS_TRAFFIC_CTRL_ERROR
11014
QoS traffic control error.
An error with the underlying traffic control (TC) API as the generic QoS request was converted for local enforcement by the TC API. This could be due to an out of memory error or to an internal QoS provider error.

WSA_QOS_GENERIC_ERROR
11015
QoS generic error.
A general QoS error.

WSA_QOS_ESERVICETYPE
11016
QoS service type error.
An invalid or unrecognized service type was found in the QoS flowspec.

WSA_QOS_EFLOWSPEC
11017
QoS flowspec error.
An invalid or inconsistent flowspec was found in the QOS structure.

WSA_QOS_EPROVSPECBUF
11018
Invalid QoS provider buffer.
An invalid QoS provider-specific buffer.

WSA_QOS_EFILTERSTYLE
11019
Invalid QoS filter style.
An invalid QoS filter style was used.

WSA_QOS_EFILTERTYPE
11020
Invalid QoS filter type.
An invalid QoS filter type was used.

WSA_QOS_EFILTERCOUNT
11021
Incorrect QoS filter count.
An incorrect number of QoS FILTERSPECs were specified in the FLOWDESCRIPTOR.

WSA_QOS_EOBJLENGTH
11022
Invalid QoS object length.
An object with an invalid ObjectLength field was specified in the QoS provider-specific buffer.

WSA_QOS_EFLOWCOUNT
11023
Incorrect QoS flow count.
An incorrect number of flow descriptors was specified in the QoS structure.

WSA_QOS_EUNKOWNPSOBJ
11024
Unrecognized QoS object.
An unrecognized object was found in the QoS provider-specific buffer.

WSA_QOS_EPOLICYOBJ
11025
Invalid QoS policy object.
An invalid policy object was found in the QoS provider-specific buffer.

WSA_QOS_EFLOWDESC
11026
Invalid QoS flow descriptor.
An invalid QoS flow descriptor was found in the flow descriptor list.

WSA_QOS_EPSFLOWSPEC
11027
Invalid QoS provider-specific flowspec.
An invalid or inconsistent flowspec was found in the QoS provider-specific buffer.

WSA_QOS_EPSFILTERSPEC
11028
Invalid QoS provider-specific filterspec.
An invalid FILTERSPEC was found in the QoS provider-specific buffer.

WSA_QOS_ESDMODEOBJ
11029
Invalid QoS shape discard mode object.
An invalid shape discard mode object was found in the QoS provider-specific buffer.

WSA_QOS_ESHAPERATEOBJ
11030
Invalid QoS shaping rate object.
An invalid shaping rate object was found in the QoS provider-specific buffer.

WSA_QOS_RESERVED_PETYPE
11031
Reserved policy QoS element type.
A reserved policy element was found in the QoS provider-specific buffer.

Requirements

Requirement Value
Header
Winsock2.h;
Winerror.h

See also

Error Codes — errno, h_errno and WSAGetLastError

Handling Winsock Errors

FormatMessage

WSAGetLastError

02.08.2011, 23:42. Показов 1586. Ответов 2


Студворк — интернет-сервис помощи студентам

Уже всё перепробовал, но больше идей никаких нет.. =(
Клиент:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
WS = WSAStartup(MAKEWORD(2,0), (WSADATA *)&buff[0]);
if (WS == SOCKET_ERROR) {MessageBox(MainWindowHandle,L"Ошибка WSAStartup",L"Ошибка при соединении",0);}
sock = socket(AF_INET, SOCK_STREAM,0);
if (sock == INVALID_SOCKET) {MessageBox(MainWindowHandle,L"Ошибка socket",L"Ошибка при соединении",0);}
ip.sin_addr.S_un.S_addr = inet_addr(ipc);
con = connect(sock, (sockaddr *) &ip, sizeof(ip));
if (con == INVALID_SOCKET) {
MessageBox(MainWindowHandle,L"Ошибка connect",L"Ошибка при соединении",0);
} else {
sen = send(sock,dat,sizeof(dat),0);
if (sen == SOCKET_ERROR) {
 MessageBox(MainWindowHandle,L"Ошибка send",L"Ошибка при соединении",0);
} else {
 MessageBox(MainWindowHandle,L"Сообщение успешно отправлено!",L"Уведомление о сообщении",0);
}
}
closesocket(con);
closesocket(sock);
WSACleanup();
return 0;

Сервер:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
DWORD __stdcall ServerFunction(void*) {
WS = WSAStartup(MAKEWORD(2,0), (WSADATA *)&buff[0]);
if (WS == SOCKET_ERROR) {MessageBox(MainWindowHandle,L"Ошибка WSAStartup",L"Ошибка при соединении",0);}
sock = socket(AF_INET, SOCK_STREAM,0);
if (sock == INVALID_SOCKET) {MessageBox(MainWindowHandle,L"Ошибка socket",L"Ошибка при соединении",0);}
bind(sock,(sockaddr *) &sa, sizeof(sa));
while (1) {
int list = listen(sock,1);
MessageBox(MainWindowHandle,L"Шаг 1",L"Информация",0);
if (list != INVALID_SOCKET) {
MessageBox(MainWindowHandle,L"Шаг 2",L"Информация",0);
con2 = accept(sock,0,0);
MessageBox(MainWindowHandle,L"Шаг 3",L"Информация",0);
int rec = recv(con2,(char *) &dat2, 150, 0);
if (rec == SOCKET_ERROR) {MessageBox(MainWindowHandle,L"Ошибка recv",L"Ошибка при соединении",0);}
else {MessageBoxA(MainWindowHandle,dat2,"Получено сообщение!",0);}
}
MessageBox(MainWindowHandle,L"Шаг 4",L"Информация",0);
Sleep(1000);
}
closesocket(con2);
closesocket(sock);
WSACleanup();
return 0;
}

На локалхосте всё хорошо, а с друзьями — клиент пытается подключиться к серверу, но там ошибка таймаута. А сервер тем временем выводит «Шаг 1», «Шаг 2» и больше ничего.
И, кстати, до этого был listen — я поставил до него MessageBox и после. Он вывел оба MessageBox’а друг за другом. А это значит, что listen не ожидая соединения закончил свою работу? Оо



0



  • Ошибка подключения сети 102
  • Ошибка подключения принтера 0x000003eb
  • Ошибка подключения поднесите браслет ближе к вашему телефону mi band 4
  • Ошибка подключения сетевой кабель не подключен
  • Ошибка подключения принтера 0x00000043