source:
http://www.vckbase.com/document/viewdoc/?id=1036
WinSock study notes (b) Author: Xiao Jin some functions related to the introduction socket 1, read the current error value: Each time an error occurs, if you want to deal with specific issues, then you should call this function to get the error code. Int Wsagetlasterror (void);
#define h_errno wsagetlasterror ()
If you do your error, please read Winsock2.h yourself. 2. Convert the host's unsigned long value to network byte order (32 digits): Why do you do this? Data is stored in different bytes using different computers. Therefore, any IP address and port number from the Winsock function to the IP address and port number and the IP address and port number passing to the Winsock function are organized according to the network sequence. U_long htonl (u_long hostlong);
Example: htonl (0) = 0
HTONL (80) = 1342177280
3. Transfer the Unsigned long number from the network byte sequence sequence, which is the inverse function of the above function. U_long ntohl; u_long netlong);
Example: NTOHL (0) = 0
Ntohl (1342177280) = 80
4. Convert the host's unsigned short value to network byte sequence (16 bits): Cause 2: u_short htons (u_short hostshort);
Example: htonl (0) = 0
HTONL (80) = 20480
5. Transfer the number of host byte sequence from the network byte order, is the inverse function of the above function. U_SHORT NTOHS (U_SHORT NETSHORT);
Example: NTOHS (0) = 0
NTOHSL (20480) = 80
6. The address of the IP address will be converted to the address of the IN_ADDR structure, and the definition of this structure sees notes (a), actually a unsigned long value. The internal processing of the IP address is not recognized as data such as 192.1.8.8.8. Unsigned long inet_addr (const char far * cp);
Example: INET_ADDR ("192.1.8.84") = 1409810880
INET_ADDR ("127.0.0.1") = 16777343
If an error occurs, the function returns the INADDR_NONE value. 7. The IP address divided by the network address conversion bit segmentation is the inverse function of the above function. Char Far * inet_ntoa (struct in_addr in);
Example: char * ipaddr = null;
Char Addr [20];
IN_ADDR INADDR;
INADDR. s_addr = 16777343;
ipaddr = inet_ntoa (inaddr);
STRCPY (AddR, IPADDR); thus the value of ADDR becomes 127.0.0.1. Note not to modify the return value or perform the release action. If the function fails, the null value will be returned. 8, get the local address structure of the socket: int GetSockName (Socket S, Struct Sockaddr Far * Name, Int Far * Namelen);
S is a socket
Name is the address value obtained after the function call
Namelen is the size of the buffer.
9, get the end address structure connected to the socket: int GETPEERNAME (Socket S, Struct SockAddr Far * Name, INT FAR * Namelen); S is a socket
Name is the end address value obtained after the function call
Namelen is the size of the buffer.
10, get the computer name: int gethostname (Char Far * name, int namelen);
Name is a buffer that stores a computer name
Namelen is the size of the buffer
usage:
Char szname [255];
MEMSET (SZNAME, 0, 255);
IF (gethostname (SZNAME, 255) == Socket_ERROR)
{
// Error handling
}
The return value is: sznmae = "xiaojin"
11, get the host address according to the computer name: Struct Hostent Far * gethostByname (Const Char Far * Name);
Name is the computer name.
usage:
Hostent * host;
Char * IP;
Host = gethostbyname ("xiaojin");
IF (Host-> h_addr_list [0])
{
Struct in_addr addr;
Memmove (& Addr, Host-> H_ADDR_LIST [0], 4);
// Get standard IP addresses
IP = INET_ NTOA (AddR);
}
The return value is: hostent-> h_name = "xiaojin"
Hostent-> h_addrtype = 2 // af_inet
Hostent-> Length = 4
IP = "127.0.0.1"
Winsock's I / O operation: 1, two I / O modes
Blocking mode: Allowed before performing I / O operation, it will not be sent to the program. Sockets defaults to block mode. It can be processed by multi-threading technology. Non-blocking mode: When performing I / O operation, the Winsock function returns and hands over the control. This mode is more complicated because the function returns to return without running, and will return WSAEWOULDBLOCK errors. But power is powerful. In order to solve this problem, some I / O models for I / O operations are proposed, and the three most common: 2, SELECT model: You can determine the status of one or more sockets by calling the SELECT function. Is there a data on the text, or whether it can write data to a socket. Int Select (int NFDS, FD_SET FAR * READFDS, FD_SET FAR * WRITEFDS,
FD_SET FAR * EXCEPTFDS, Const Struct TimeVal Far * Timeout
◆ Let's first look at the definition of the structure involved: a, d_set structure: #define fd_setsize 64?
Typedef struct fd_set {
u_int fd_count; / * How much is set? * /
Socket FD_Array [FD_SETSIZE]; / * an Array of Sockets * /
} fd_set; fd_count is the number of fd_array that has been set to the Socket for the Socket list, fd_setsize is the maximum Socket number, and it is recommended not less than 64. This is Microsoft proposal. B, TimeVal structure: struct timeval {
Long TV_sec; / * seconds * /
Long TV_usec; / * and microseconds * /
}
TV_sec is the second value of time. TV_USEC is a millisecond value. This structure is mainly to set the wait value of the select () function, if the structure is set to (0, 0), then the select () function returns immediately. ◆ Let's take a look at the roles of the parameters of the SELECT function:
NFDS: There is no use, mainly used for system compatibility, generally set to 0. ReadFDS: Sockets Wait for readability check. Writefds; Sockets Wait for a writeable check. Exceptfds: Sockets waiting for an error check. Timeout: Timeout. The return value of the function failed: call failed to return to Socket_ERROR, timeout returns 0. Readfds, Writefds, ExceptFDS three variables at least one is not empty, and this is not empty socket group of at least one socket, which is very simple, otherwise SELECT does it. Example: Test if a socket reads: fd_set fdread;
// fd_zero definition
// #define fd_zero ((FD_SET FAR *) (SET)) -> fd_count = 0)
FD_ZERO (& FDREAD);
FD_set (s, & fdread); // Add to the socket, detailed definition, please see Winsock2.h
IF (SELECT (0,% FDRead, Null, Null, Null> 0
{
//success
IF (fd_isset (s, & fread) // is existing in FREAD, please see Winsock2.h in detail
{
// is readable
}
} ◆ I / O operation function: Mainly used to obtain operational parameters related to the socket. INT IOCTLSOCKET (Socket S, Long CMD, U_LONG FAR * ARGP); S is the I / O operation socket. CMD is an operation command for a socket. Argp is a pointer to the parameters of the command. Common command: / / Determine the amount of data automatically read in the socket
#define fion_ior ('' '' f '' '', 127, u_long) / * get # BYTES to read * /
/ / Allow or prohibit the non-blocking mode of the socket, allowing for non-0, forbidden to 0
#define fionbio _iow ('' '' F '' ', 126, U_LONG) / * SET / CLEAR NON-block I / O * /
/ / Determine if all of the extracted data has been read
#define siocatmark_ior ('' '' 's' '', 7, u_long) / * at OOB Mark? * /
3, WSaasynselect Model: The WSaasynselect model is also a common asynchronous I / O model. Applications can receive network event notifications based on Windows messages on a socket. The implementation method of this model is to automatically set the socket to a non-blocking mode by calling the WSAAsYNselect function, and register one or more network times to Windows, and provides a window handle used when notification. When the registered event occurs, the corresponding window will receive a message-based notification. INT WSAASYNCSELECT (Socket S, HWND HWND, U_INT WMSG, long]; S is the network of the application that is interested in the message LEVENT for the received message, which is required to receive the message, where the message is notified. The event combination, mainly the following: #define fd_read_bit 0 # define fd_read (1 << fd_read_bit)
#define fd_write_bit 1
#define fd_write (1 << fd_write_bit)
#define fd_oob_bit 2
#define fd_oob (1 << fd_oob_bit)
#define fd_accept_bit 3
#define fd_accept (1 << fd_accept_bit)
#define FD_CONNECT_BIT 4
#define fd_connect (1 << fd_connect_bit)
#define fd_close_bit 5
#define fd_close (1 << fd_close_bit)
Usage: To receive read and write notifications: int NRESULT = WSAASYNCSELECT (S, HWnd, WMSG, FD_READ | FD_WRITE);
IF (NResult == Socket_ERROR)
{
// Error handling
}
Cancel notification: int NRESULT = WSAASYNCSELECT (S, HWND, 0, 0);
When the application window hWnd receives the message, the WMSG.WParam parameter identifies the socket, the low word of LParam indicates the network event, and the high character contains the error code. 4, WSAEventSelect model WSAEventselectSelect model Similar to WSaasynselect model, but the most important difference is that the network event occurs when it occurs to an event object handle, not to a window. The following steps are as follows: a, create an event object to receive network events: #define WSAEvent Handle
#define lpwsaevent lphandle
WSAEVENT WSACREATEEVENT (VOID);
The return value of this function is an event object handle, which has two working states: signaling and unauthorized and two working modes: manual reset and automatic reset (Auto RESET). Unfaults of unidentified work status and artificial reset mode. b, associate event objects with sockets, simultaneously register events, so that the operating status of the event object has never been communicated. INT WSAEventSelect (Socket S, WSAEvent HEVENTOBJECT (SONG LNETWORKEVENTS); S is a mask for the event object handle LNetworkEvents, which is created, is defined as described above. Letter wsaresetevent (WSAEvent HEVENT); HEVENT successfully returns true to the event object, failed to return false. D, waiting for network events to trigger the working status of the event handle: DWORD WSAWAITFORMULTIPLEEVENTS (DWord Cevents, Const WSaevent Far * Lphevents, Bool Fwaitall,
DWORD DWTIMEOUT, BOOL FALERTABLE); LPEVENT is the number of pointer CEVENT for the event handle, which is the number of event handles, and its maximum value is WSA_Maximum_wait_events fwaitall Specifies a wait type: True: Return when all event objects are over-all event objects; false: An event is returned. DWTIMEOUT Waizards whether the completion routine is noted when returning to the specified function (milliseconds) falertable, when the completion of the completion routine is referenced, the return value of WSAWAITFORMULTIPEVENTS should be used, and the pre-sound value WSA_WAIT_EVENT_0 is subtracted, and the specific reference value is obtained. For example: nindex = wsawaitformultipleevents (...);
MyEvent = EventArray [INDEX-WSA_WAIT_EVENT_0]; E, Judgment Network Event Type: Int WSAenumNetworkEvents (Socket S,
WSAEvent HEVENTOBJECT, LPWSANETWORKEVENTS LPNETWORKEVENTS; S is a socket HEVENTOBJECT for the Reset Event Object LpNetwork Events for recording network events and error codes, the structure is defined as follows: typedef struct _wsanetworkEvents {
Long LnetWorkevent;
INT IERRORCODE [FD_MAX_EVENTS];
} WSANETWORKEVENTS, FAR * LPWSANETWORKEVENTS; F, close the event object handle: BOOL WSACLOSEEVENT (WSAEvent HEVENT); call successfully returns true, otherwise returns false. Author brief introduction Xiao Jin Nanjing Zhongzi Food Co., Ltd. Information Email: xiaoj@njb.swirebev.com Tel: 025-58642091