Recently I wrote a stuff related to network communication, so I've been more in this area, I collected some, so that I will find it later!
Some functions related to Socket
1. Read the current error value: When an error occurs, if you want to process the specific problem, 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 order (16 digits): Cause 2:
U_SHORT HTONS (u_short hostshst);
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 The end address value Namelen obtained after the function call 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 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 operation are proposed, and three of the most common:
2, SELECT model:
By calling the SELECT function, you can determine the state of one or more sockets, and determine whether there is data on the sleeve, or
Whether to 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 take a 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 set Sockets
fd_array is the Socket list, fd_setsize is the maximum number of sockets, and it is recommended not less than 64. This is Microsoft
Discussed.
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
There is at least one Socket, which is very simple, otherwise SELECT is doing. Example: Test if a socket is readable:
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 commands:
/ / 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 commonly used asynchronous I / O model. Applications can receive on a socket
Network event notifications based on Windows messages. The method of this model is to call the WSAAsYNselect letter.
The number automatically sets the socket to non-blocking mode and register one or more network times to Windows, and provides one
The window handle used when notifications. When the registered event occurs, the corresponding window will receive a message-based notification.
INT WSAASYNCSELECT (Socket S, HWND HWND, U_INT WMSG, Long LEVENT); S is a socket that requires event notification
HWnd is a window handle for receiving a message
WMSG is the message to receive
Levent is a mask, specifying the network event combination of application interested, mainly below:
#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, LPARM's low words indicate
The network event, high character contains an error code.
4, WSAEventselect Model
The WSAEventselect model is similar to the WSaasynselect model, but the most important difference is that the online event will be sent.
Send to an event object handle instead of sending to a window.
The steps are as follows:
A. Creating 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: signals (signals) and unauthorized
(Nonsignaled) and two working modes: Manual Reset and Auto Reset. Default
Unidentified working 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 transformed
It has been submitted.
INT WSAEventSelect (Socket S, WSAEvent HEVENTOBJECT, LONG LNETWORKEVENTS); S is a socket
HEVENTOBJECT is a handle of an event object created
LnetWorKevents is a mask, defined as described above.
After C, I / O treatment, set the event object as unidentified
Bool Wsaresete (WSAEvent HEVENT);
HEVENT successfully returns true to the event object, failed to return false. D, waiting for network events to trigger the operating status of the event handle:
DWORD WSAWAITFORMULTIPEEVENTS (DWORD CEVENTS,
Const WSAEVENT FAR * LPHEVENTS, BOOL FWAITALL,
DWORD DWTIMEOUT, BOOL FALERTABLE;
LPEVENT is the number of event handle arguments to the number of event handles, whose maximum value is WSA_Maximum_wait_events fwaitall Specifies a wait type: TRUE: Return when all event objects are over-all event objects; false: Return to any event. 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, judge the type of network event:
Int WSAenumNetworkEvents (socket S,
WSAEvent HEVENTOBJECT, LPWSANETWORKEVENTS LPNETWORKEVENTS
s The SLR HEVENTOBJECT for the Reset Event Object LpNetWorKevents is a record network event and an error code, which 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.