Basic knowledge of Windows Network Programming and basic knowledge of Network Programming
1. WinSock Initialization
# Include <iostream> # include <WinSock2.h> # include <MSWSock. h> # pragma comment (lib, "WS2_32.lib") // when using WinSock2.h, the using namespace std must be loaded; // The Winsock2 function carries the WSA prefix, except WSAStartup WSACleanup WSARecvEX WSAGetLastErrorint main () {WSADATA wsData; if (SOCKET_ERROR = WSAStartup (MAKEWORD (2, 2), & wsData )) // The first 2 is the minor version {cout <"initialization error! "<Endl ;}cout <" main version: "<(int) LOBYTE (wsData. wHighVersion) <endl; // cout <"minor version" <(int) HIBYTE (wsData. wHighVersion) <endl; WSACleanup (); system ("pause"); return-1 ;}
2. Check and handle errors
WSAGetLastErrorWSASetLastError manually sets the error code
3.
typedef struct sockaddr_in { ADDRESS_FAMILY sin_family; USHORT sin_port; IN_ADDR sin_addr; CHAR sin_zero[8];} SOCKADDR_IN, *PSOCKADDR_IN;
Sin_family must be AF_INET, which indicates that WinSock uses an IP address family.
Sin_zero [8] only acts as a fill item, so that SOCKADDR_IN and SOCKADDR have the same structure length. SOCKADDR is a common socket address and serves as void *.
Byte sorting
Different computer processors may be encoded in the form of big-endian or little-endian. The multi-byte value specified by Internet standards must be expressed in the big-endian format, which is generally called the network byte sequence.
The following four common API functions convert the number of bytes from the host to the network byte order:
WSAHtonl // 4-byte htonlWSAHtons // 2-byte htons
Otherwise
WSANtohlntohlWSANtohsntohs
Another common function is to convert the IP address to a 4-byte integer.
SrvAddr. sin_addr.S_un.S_addr = inet_addr ("127.0.0.1 ");
SOCKADDR_IN srvAddr;srvAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);srvAddr.sin_family = AF_INET;srvAddr.sin_port = htons(DefaultPort);
INADDR_ANY indicates all the ports sent to the server. No matter which network adapter/IP address receives the data, it is handed over to the socket for processing.