Netsh Winsock — что это и зачем нужно?
При поиске решений проблем с сетевыми подключениями в интернете пользователи рано или поздно попадают на сайты, на которых говорится о необходимости сброса настроек TCP/IP при помощи специфических команд — netsh winsock reset. Разберемся, что это вообще такое.
Netsh
В приведенной выше команде winsock является только «вложением» (контекстом) в основную команду — netsh. Netsh — это небольшая системная программа (сетевая оболочка), предназначенная для управления сетевыми параметрами Windows и конфигурирования параметров интерфейсов связи сетевых устройств (сетевых плат/адаптеров).
Назначений у программы Netsh довольно много, но чаще всего она используется именно для сброса рабочих параметров TCP/IP. Кроме того, при помощи этой программы (команды) можно изменять IP-адрес, маску подсети, основной шлюз и DNS-сервер любого существующего сетевого подключения (интерфейса).
Winsock
Как отмечалось выше, winsock — один из многочисленных контекстов (будем называть параметров) основной команды netsh. По сути — это техническая спецификация, определяющая способы взаимодействия всего установленного программного обеспечения с сетевыми сервисами, включая TCP/IP. Если простыми словами, Winsock «указывает» какой-либо сетевой программе (браузеру, например), к какому из доступных сетевых подключений ей обращаться для передачи данных во внешнюю сеть.
Как использовать Netsh?
Не будем изобретать велосипед и в качестве примера приведем команды для сброса настроек TCP/IP и изменения основных сетевых параметров одного из подключений.
Сброс TCP/IP при помощи Netsh. Первым делом нужно запустить командную строку Windows от имени администратора (в противном случае система откажет в доступе к своим настройкам):
- Введите в поисковую строку Windows, что расположена в/около меню «Пуск», фразу «командная строка».
- В результатах поиска кликните правой кнопкой мыши по найденному элементу «Командная строка», затем выберите пункт «Запустить от имени администратора».
Для сброса сетевой конфигурации системы обычно достаточно использовать две команды:
netsh int ip reset
netsh winsock reset
Введите их последовательно (завершая ввод клавишей «Enter») в окно командной строки.
В сети по-прежнему можно найти инструкции по сбросу TCP/IP, в которых первой используется другая команда: netsh int ip reset all. В Windows 10 эта команда не работает. Попробуйте ввести ее, получите ошибку. Очень жаль, потому что в параметре int команды netsh содержатся настройки не только для ip, но и для других сетевых объектов.
Если использование netsh int ip reset оказалось недостаточным для «ремонта» сетевого подключения, всегда можно сбросить и другие параметры int, поочередно вводя:
netsh int httpstunnel reset
netsh int ipv6 reset
netsh int tcp reset
netsh int portproxy reset
Если и это не поможет восстановить работоспособность сетевого подключения, проблему следует искать где-нибудь в другом месте (в драйвере, например).
Смена основных сетевых параметров при помощи Netsh. Конечно, эти параметры легче изменить стандартным способом — через свойства интернет-протокола IPv4 конкретного сетевого подключения. Но все же не будет лишним научиться делать это и через Windows-консоль, ведь стандартный способ может и не сработать, особенно, если компьютер заражен каким-нибудь вирусом-блокировщиком.
Для начала нужно узнать имя сетевого интерфейса, с которым предстоит работать. Для этого используем команду:
netsh int show interface
В нашем случае имеется всего одно единственное подключение, имя которого — Ethernet (это обычное подключение по локальной сети).
Меняем IP-адрес, маску подсети и основной шлюз на требуемом интерфейсе. Для этого используем команду:
netsh int ip set address ethernet static 192.168.0.25 255.255.255.0 192.168.0.1
- Параметр ethernet — имя перенастраиваемого сетевого подключения. Если в имени содержаться пробелы (например, оно названо «Подключение по локальной сети Ethernet»), его необходимо писать в кавычках — » Подключение по локальной сети Ethernet «.
- Параметр static указывает, что устанавливаемые сетевые параметры будут являться статичными. Т.е. процедура по смене IP, маски и шлюза через командную строку равнозначна процедуре смены сетевых параметров стандартным способом.
- Параметр 168.0.25 — новый IP-адрес для нашего подключения.
- Параметр 255.255.0 — новая маска подсети.
- Параметр 168.0.1 — новый основной шлюз.
Возникает вопрос — а где новый DNS-сервер? Этот параметр не является обязательным — он, скорее, добавочный. Т.е. нам предстоит добавить новый элемент в наше сетевое подключение. Делается это следующим образом:
netsh int ip add dnsserver ethernet 8.8.4.4
Здесь, впрочем, все понятно. Указанный нами DNS-сервер — это общедоступный сервер от Google. Вы можете использовать вместо него DNS, выданный вашим интернет-провайдером.
Кстати, если использовать команду повторно с другим адресом DNS-сервера, он запишется в поле «Альтернативный DNS-сервер».
Результат выполнения команды можно посмотреть в свойствах сетевого подключения:
Сброс Winsock в Windows: для чего он нужен и зачем это делать
Наличие хорошего интернет-соединения очень важно для нормальной навигации, загрузки с хорошей скоростью и избежания постоянных обрывов. Есть много факторов, которые могут повлиять на сеть, но в большинстве случаев мы сможем их контролировать. В этой статье мы поговорим о как сбросить винсок in Windows и почему это то, что может помочь нашему интернет-соединению работать лучше.
Что такое Winsock и для чего он нужен?
Имя Винсока происходит от Разъем Windows . Можно сказать, что это программный интерфейс, который используется для установления связи между сетевым программным обеспечением Windows и сетевыми службами. Он использует протокол TCP/IP, чтобы программы, которым необходим доступ к Интернету, могли подключаться.
Это в основном служит для того, чтобы программы могут подключаться к Интернету . Например, приложение для обмена сообщениями, программа для загрузки файлов в облако и т. д. Любое приложение, которое вы установили в Windows и которому для работы требуется доступ к сети, будет зависеть от Winsock.
Несмотря на то, что он входит в стандартную комплектацию Microsoft операционных системах, мы также можем найти его в других, таких как macOS. Это не что-то новое, так как оно было создано несколько десятилетий назад. Со временем он адаптировался к новым версиям системы и к потребностям программ, которые мы устанавливаем.
Можно сказать, что Винсок отвечает за прием и отправка запросов . Что он делает, так это транслирует запросы для выполнения различных задач, требующих использования протокола TCP/IP. Таким образом, это необходимый инструмент для многих функций, которые мы выполняем в повседневной жизни в Интернете. Если что-то пойдет не так, если возникнет проблема, она не сможет работать правильно, и нам придется принять определенные меры, чтобы программы, зависящие от этой функции, могли выполняться правильно.
Почему полезно сбросить Netsh Winsock
Так чем же интересно сбросить Winsock? Уинсок будет хранить важную информацию о том, как эти приложения и коммуникации будут взаимодействовать. Эта база данных может быть повреждена и перестать работать должным образом. Например, если на компьютер проник вирус, неправильная конфигурация системы, неудачное обновление и т. д. Имейте в виду, что то, что мы упомянули, также может повлиять на просмотр, хотя это не то, что напрямую влияет на эту функцию Windows.
Это приведет к тому, что приложения не смогут нормально подключаться к Интернету. Вы можете увидеть сбои скорости, постоянные сбои или даже невозможность подключения. В этом случае начнут появляться сообщения о том, что приложению не удалось подключиться, или сообщения об ошибках, связанные с Winsock. Это в том случае, когда мы должны были бы принять меры для достижения оптимальной работы.
Winsock tutorial – Socket programming in C on windows
This is a quick guide/tutorial to learning socket programming in C language on Windows. «Windows» because the code snippets shown over here will work only on Windows. The windows api to socket programming is called winsock.
Sockets are the fundamental «things» behind any kind of network communications done by your computer. For example when you type www.google.com in your web browser, it opens a socket and connects to google.com to fetch the page and show it to you.
Same with any chat client like gtalk or skype. Any network communication goes through a socket.
Before you begin
This tutorial assumes that you have basic knowledge of C and pointers. Also download Visual C++ 2010 Express Edition.
Initialising Winsock
Winsock first needs to be initialiased like this :
winsock2.h is the header file to be included for winsock functions. ws2_32.lib is the library file to be linked with the program to be able to use winsock functions.
The WSAStartup function is used to start or initialise winsock library. It takes 2 parameters ; the first one is the version we want to load and second one is a WSADATA structure which will hold additional information after winsock has been loaded.
If any error occurs then the WSAStartup function would return a non zero value and WSAGetLastError can be used to get more information about what error happened.
OK , so next step is to create a socket.
Creating a socket
The socket() function is used to create a socket.
Here is a code sample :
Function socket() creates a socket and returns a socket descriptor which can be used in other network commands. The above code will create a socket of :
Address Family : AF_INET (this is IP version 4)
Type : SOCK_STREAM (this means connection oriented TCP protocol)
Protocol : 0 [ or IPPROTO_TCP , IPPROTO_UDP ]
It would be a good idea to read some documentation here
Ok , so you have created a socket successfully. But what next ? Next we shall try to connect to some server using this socket. We can connect to www.google.com
Note
Apart from SOCK_STREAM type of sockets there is another type called SOCK_DGRAM which indicates the UDP protocol. This type of socket is non-connection socket. In this tutorial we shall stick to SOCK_STREAM or TCP sockets.
Connect to a Server
We connect to a remote server on a certain port number. So we need 2 things , IP address and port number to connect to.
To connect to a remote server we need to do a couple of things. First is create a sockaddr_in structure with proper values filled in. Lets create one for ourselves :
Have a look at the structures
The sockaddr_in has a member called sin_addr of type in_addr which has a s_addr which is nothing but a long. It contains the IP address in long format.
Function inet_addr is a very handy function to convert an IP address to a long format. This is how you do it :
So you need to know the IP address of the remote server you are connecting to. Here we used the ip address of google.com as a sample. A little later on we shall see how to find out the ip address of a given domain name.
The last thing needed is the connect function. It needs a socket and a sockaddr structure to connect to. Here is a code sample.
It cannot be any simpler. It creates a socket and then connects. If you run the program it should show Connected.
Try connecting to a port different from port 80 and you should not be able to connect which indicates that the port is not open for connection.
OK , so we are now connected. Lets do the next thing , sending some data to the remote server.
Quick Note
The concept of «connections» apply to SOCK_STREAM/TCP type of sockets. Connection means a reliable «stream» of data such that there can be multiple such streams each having communication of its own. Think of this as a pipe which is not interfered by other data.
Other sockets like UDP , ICMP , ARP dont have a concept of «connection». These are non-connection based communication. Which means you keep sending or receiving packets from anybody and everybody.
Sending Data
Function send will simply send data. It needs the socket descriptor , the data to send and its size.
Here is a very simple example of sending some data to google.com ip :
In the above example , we first connect to an ip address and then send the string message «GET / HTTP/1.1\r\n\r\n» to it.
The message is actually a http command to fetch the mainpage of a website.
Now that we have send some data , its time to receive a reply from the server. So lets do it.
Receiving Data
Function recv is used to receive data on a socket. In the following example we shall send the same message as the last example and receive a reply from the server.
'; puts(server_reply); return 0; >
Here is the output of the above code :
We can see what reply was send by the server. It looks something like Html, well IT IS html. Google.com replied with the content of the page we requested. Quite simple!
Now that we have received our reply, its time to close the socket.
Close socket
Function closesocket is used to close the socket. Also WSACleanup must be called to unload the winsock library (ws2_32.dll).
Lets Revise
So in the above example we learned how to :
1. Create a socket
2. Connect to remote server
3. Send some data
4. Receive a reply
Its useful to know that your web browser also does the same thing when you open www.google.com The other kind of socket activity is called a SERVER. A server is a system that uses sockets to receive incoming connections and provide them with data. It is just the opposite of Client. So www.google.com is a server and your web browser is a client. Or more technically www.google.com is a HTTP Server and your web browser is an HTTP client.
This kind of socket activity represents a CLIENT . A client is a system that connects to a remote system to fetch or retrieve data.
Now its time to do some server tasks using sockets. But before we move ahead there are a few side topics that should be covered just incase you need them.
Get IP address of a hostname/domain
When connecting to a remote host , it is necessary to have its IP address. Function gethostbyname is used for this purpose. It takes the domain name as the parameter and returns a structure of type hostent. This structure has the ip information. It is present in netdb.h . Lets have a look at this structure
The h_addr_list has the IP addresses. So now lets have some code to use them.
Output of the code would look like :
So the above code can be used to find the ip address of any domain name. Then the ip address can be used to make a connection using a socket.
Function inet_ntoa will convert an IP address in long format to dotted format. This is just the opposite of inet_addr .
So far we have see some important structures that are used. Lets revise them :
1. sockaddr_in — Connection information. Used by connect , send , recv etc.
2. in_addr — Ip address in long format
3. sockaddr
4. hostent — The ip addresses of a hostname. Used by gethostbyname
Server Concepts
OK now onto server things. Servers basically do the following :
1. Open a socket
2. Bind to a address(and port).
3. Listen for incoming connections.
4. Accept connections
5. Read/Send
We have already learnt how to open a socket. So the next thing would be to bind it.
Bind a socket
Function bind can be used to bind a socket to a particular address and port. It needs a sockaddr_in structure similar to connect function.
Lets see a code example :
Now that bind is done, its time to make the socket listen to connections. We bind a socket to a particular IP address and a certain port number. By doing this we ensure that all incoming data which is directed towards this port number is received by this application.
This makes it obvious that you cannot have 2 sockets bound to the same port.
Listen for connections
After binding a socket to a port the next thing we need to do is listen for connections. For this we need to put the socket in listening mode. Function listen is used to put the socket in listening mode. Just add the following line after bind.
Thats all. Now comes the main part of accepting new connections.
Accept connection
Function accept is used for this. Here is the code
Output
Run the program. It should show
So now this program is waiting for incoming connections on port 8888. Dont close this program , keep it running.
Now a client can connect to it on this port. We shall use the telnet client for testing this. Open a terminal and type
And the server output will show
So we can see that the client connected to the server. Try the above process till you get it perfect.
Note
You can get the ip address of client and the port of connection by using the sockaddr_in structure passed to accept function. It is very simple :
We accepted an incoming connection but closed it immediately. This was not very productive. There are lots of things that can be done after an incoming connection is established. Afterall the connection was established for the purpose of communication. So lets reply to the client.
Here is an example :
Run the above code in 1 terminal. And connect to this server using telnet from another terminal and you should see this :
So the client(telnet) received a reply from server. We had to use a getchar because otherwise the output would scroll out of the client terminal without waiting
We can see that the connection is closed immediately after that simply because the server program ends after accepting and sending reply. A server like www.google.com is always up to accept incoming connections.
It means that a server is supposed to be running all the time. Afterall its a server meant to serve. So we need to keep our server RUNNING non-stop. The simplest way to do this is to put the accept in a loop so that it can receive incoming connections all the time.
Live Server
So a live server will be alive for all time. Lets code this up :
We havent done a lot there. Just the accept was put in a loop.
Now run the program in 1 terminal , and open 3 other terminals. From each of the 3 terminal do a telnet to the server port.
Run telnet like this. It will launch the interactive prompt.
At the telnet shell, run the command «open localhost 8888». This command will try to connect to localhost on port number 8888.
Next you should see the following message at the telnet prompt. This message is received from the socket server running on port 8888.
On the other hand, the server terminal would show the following messages, indicating that a client connected to it.
So now the server is running nonstop and the telnet terminals are also connected nonstop. Now close the server program.
All telnet terminals would show «Connection to host lost.»
Good so far. But still there is not effective communication between the server and the client.
The server program accepts connections in a loop and just send them a reply, after that it does nothing with them. Also it is not able to handle more than 1 connection at a time. So now its time to handle the connections , and handle multiple connections together.
Handling Connections
To handle every connection we need a separate handling code to run along with the main server accepting connections.
One way to achieve this is using threads. The main server program accepts a connection and creates a new thread to handle communication for the connection, and then the server goes back to accept more connections.
We shall now use threads to create handlers for each connection the server accepts. Lets do it pal.
Run the above server and open 3 terminals like before. Now the server will create a thread for each client connecting to it.
The telnet terminals would show :
This one looks good , but the communication handler is also quite dumb. After the greeting it terminates. It should stay alive and keep communicating with the client.
One way to do this is by making the connection handler wait for some message from a client as long as the client is connected. If the client disconnects , the connection handler ends.
So the connection handler can be rewritten like this :
The above connection handler takes some input from the client and replies back with the same. Simple! Here is how the telnet output might look
So now we have a server thats communicative. Thats useful now.
Conclusion
The winsock api is quite similar to Linux sockets in terms of function name and structures. Few differences exist like :
1. Winsock needs to be initialised with the WSAStartup function. No such thing in linux.
2. Header file names are different. Winsock needs winsock2.h , whereas Linux needs socket.h , apra/inet.h , unistd.h and many others.
3. Winsock function to close a socket is closesocket , whereas on Linux it is close .
On Winsock WSACleanup must also be called to unload the winsock dll.
4. On winsock the error number is fetched by the function WSAGetLastError() . On Linux the errno variable from errno.h file is filled with the error number.
And there are many more differences as we go deep.
By now you must have learned the basics of socket programming in C. You can try out some experiments like writing a chat client or something similar.
If you think that the tutorial needs some addons or improvements or any of the code snippets above dont work then feel free to make a comment below so that it gets fixed.
A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .
80 Comments
There is a large part of the code missing bruh
Hello, in your code you only call closesocket() to close socket “s” but you never call closesocket() to close “new_socket”
Why you only close socket “s” and not socket “new_socket” ?
you are right, new_socket should also be closed if its a valid socket.
i missed that!
Hello, in your code you call closesocket() to close a socket but you only call closesocket() to close socket “s” but you never call closesocket() to close “new_socket”?
Why you only close socket “s” and not “new_socket” ?
Introduction to Winsock Including Background & Technology [MiniTool Wiki]
What is Winsock? In computing, Winsock is a technical specification used to define how Windows network software should access network services, especially TCP/IP. It is called Winsock because it is an adaptation of the Berkeley UNIX socket interface to Windows. A socket is a special agreement used to connect with and exchange data between two program processes on the same computer or network.
Winsock is the abbreviation of the Windows Sockets API (WSA). It defines the standard interface between Windows TCP/IP client applications (such as FTP clients or Web browsers) and the basic TCP/IP protocol stack.
Background of Winsock
The Windows Sockets API was proposed by Martin Hall of JSB Software (later Stardust Technologies) in the “BoF” (Bird of a Feather) discussion on the CompuServe BBS network in October 1991.
The first version of the specification was written by Martin Hall, Mark Towfiq of Microdyne (later Sun Microsystems), Geoff Arnold of Sun Microsystems, and Henry Sanders and J Allard of Microsoft with the help of many others.
There were some discussions on how to best resolve copyright, intellectual property, and potential antitrust issues, and consideration of work through the IETF or the establishment of non-profit foundations. In the end, it was decided that the specification should only be copyrighted by five (unaffiliated) authors.
All participating developers refused to abbreviate the name to simply Winsock for a long time because there was a lot of confusion between the API and the DLL library file (winsock.dll), which only exposed the general WSA interface to the application above it. It is generally believed that only ensuring that the DLL file exists on the system can provide complete TCP/IP protocol support.
Technology of Winsock
The Windows Socket API specification defines two interfaces: API used by application developers, and SPI that provides a method for network software developers to add new protocol modules to the system. Each interface represents a contract.
The API guarantees that conforming applications can run normally with any network software vendor’s conforming protocol implementation. The SPI contract guarantees that conforming protocol modules can be added to Windows so that they can be used by API-compliant applications.
Although these contracts were important when Windows Sockets was first released, they are only of academic significance now because the network environment requires multi-protocol support. The Windows Sockets API version 2.0 includes the function of using IPX/SPX, although this protocol was almost obsolete when WSA 2.0 left the factory.
The Windows Sockets code and design are based on BSD sockets, but additional features are provided to allow the API to conform to the conventional Windows programming model.
The Windows Sockets API almost covered all the features of the BSD sockets API, but there are some inevitable obstacles, which were mainly caused by the fundamental differences between Windows and Unix (although the difference between Windows Sockets and BSD sockets was less than the difference between the latter and STREAMS).
However, the design goal of Windows sockets was to make it relatively easy for developers to port socket-based applications from Unix to Windows. It was not enough to create APIs that were only useful for newly written Windows programs.
Therefore, Windows Sockets contained many elements designed to facilitate porting. For example, Unix applications could use the same errno variable to log network errors and errors detected in standard C library functions.
Since it cannot be implemented in Windows, the Windows Sockets introduced a special function, WSAGetLastError(), to retrieve error information. Such a mechanism was very helpful, but application porting was still extremely complicated.
Many primitive TCP/IP applications have been implemented by using system features specific to Unix (such as pseudo terminals and fork system calls), and it was problematic to reproduce this function in Windows. In a relatively short time, porting gave way to the development of dedicated Windows applications.