Header file library of WinSock
Winsock has two major versions: Winsock 1 and WinSock 2, both of which can run on all Windows platforms except Windows CE (Winsock ce only supports Winsock 1. When developing window network programs, set Winsock2. H is included in the application, and the corresponding Connection Library is ws2_32.lib. The Code is as follows:
# Include <winsock2.h>
# Pragma comment (Lib, "ws2_32.lib ")
Start to initialize the Winsock library and call wsastartup (...)
Int wsastartup (
Word wversionrequested, // version number of the Winsock library, which can be makewor)
Lpwsadata // information about a library version loaded
);
After compiling a program using the Winsock interface, you should call the wsacleanup function. This function mainly releases all resources allocated by Winsock and cancels the Winsock call suspended by this application.
Int wsacleanup (void );
Now you can write a simple Winsock network program framework:
# Include <cstdlib>
# Include <iostream>
# Include <winsock2.h>
# Pragma comment (Lib, "ws2_32.lib ")
Using namespace STD;
Int main (INT argc, char * argv [])
{
Wsadata;
// Initialize Winsock 2.2
Int ret = wsastartup (makeword (2, 2), & wsadata );
If (Ret! = 0)
{
// Note: Because Winsock is not loaded, we cannot use wsagetlasterror
// To identify the specific error that causes the fault. We can only judge based on the returned status
Cout <"wsastartup failed with error" <RET <Endl;
Wsacleanup ();
Return 0;
}
// Here we create a socket to connect or listen to the code.
//......
// If the program ends, wsacleanup is called.
Wsacleanup ();
System ("pause ");
Return exit_success;
}