Winsock Study Notes (2)

Source: Internet
Author: User
Socket-related functions

1. Read the current error value: When an error occurs, if you want to handle the problem, you should call this function to obtain the error code.
      int  WSAGetLastError(void );
#define h_errno WSAGetLastError()

Read winsock2.h for the error value.

2. Convert the host's unsigned long value to the network byte sequence (32 bits): Why? Because different computers use different bytes to store data. Therefore, any reference from the Winsock function to the IP address and port number and the IP address and port number sent to the Winsock function are organized in the network order.

U_long htonl (u_long hostlong );
Example: htonl (0) = 0
Htonl (80) = 1342177280

3. Converting the unsigned long number from the byte sequence of the network to the host byte sequence 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 the network byte order (16 bits) for the same reason as 2:

U_short htons (u_short hostshort );
Example: htonl (0) = 0
Htonl (80) = 20480

5. Converting the unsigned short number from the network byte order to the host byte order is the inverse function of the above function.

U_short ntohs (u_short netshort );
Example: ntohs (0) = 0
N tohsl (20480) = 80

6. Convert the IP address separated by vertices into an in_addr structure address. for the definition of this structure, see note (1), which is actually an unsigned long value. The computer processes IP addresses internally, but does not know data such as 192.1.8.84.

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. Convert the network address into IP addresses separated by vertices, which 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 );

In this way, the ADDR value is changed to 127.0.0.1.
Do not modify the return value or release it. If the function fails, the return value is null.

8. Obtain the local address structure of the socket:

Int getsockname (socket S, struct sockaddr far * Name, int far * namelen );
S is socket
Name is the address value obtained after function call.
Namelen indicates the buffer size.

9. Obtain the end address structure connected to the socket:

Int getpeername (socket S, struct sockaddr far * Name, int far * namelen );
S is socket
Name is the end address value obtained after function call.
Namelen indicates the buffer size.

10. Obtain the computer name:

Int gethostname (char far * Name, int namelen );
Name is the buffer that stores the computer name.
Namelen indicates the buffer size.
Usage:
Char szname [255];
Memset (szname, 0,255 );
If (gethostname (szname, 255) = socket_error)
{
// Handle errors
}
Returned value: sznmae = "Xiaojin"

11. Obtain the host address based on the computer name:

Struct hostent far * gethostbyname (const char far * Name );

Name indicates 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 );
// Obtain the standard IP Address
IP = Inet _ ntoa (ADDR );
}

Returned value: hostent-> h_name = "Xiaojin"
Hostent-> h_addrtype = 2 // af_inet
Hostent-> length = 4
IP = "127.0.0.1"

Winsock I/O operations:

1. Two I/O Modes

  • Blocking Mode: wait until the I/O operation is completed, and control is not handed over to the program. The socket is in blocking mode by default. Multi-thread processing is supported.
  • Non-blocking mode: When I/O operations are performed, the Winsock function returns and gives control. This mode is complicated to use, because the function returns the wsaewouldblock error continuously if it is not completed. However, it is powerful.

To solve this problem, we propose some I/O models for I/O operations. The three most common models are described below:

2. Select model:

You can call the select function to determine the status of one or more sockets and determine whether there is data on the socket, or
Is it possible 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 take a look at the definition of the involved structure:
A. d_set structure:

#define FD_SETSIZE 64?
typedef struct fd_set {
u_int fd_count; /* how many are SET? */
SOCKET fd_array[FD_SETSIZE]; /* an array of SOCKETs */
} fd_set;

Fd_count indicates the number of socket sets.
Fd_array indicates the socket list, And fd_setsize indicates the maximum number of sockets. It is recommended that the value be no less than 64. This is Microsoft's
Discussed.

B. timeval structure:

struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* and microseconds */
};

TV _sec is the second value of the time.
TV _usec is the millisecond value of the time.
This structure mainly sets the wait value of the select () function. If the structure is set to (), the Select () function
Will return immediately.

◆ Let's take a look at the functions of the select function parameters:

  1. NFDs: it is useless and mainly used for system compatibility. It is generally set to 0.
  2. Readfds: the socket group waiting for readability check.
  3. Writefds; the socket group waiting for the writability check.
  4. Required TFDs: the socket group waiting for the error check.
  5. Timeout: timeout.
  6. Return Value of function failure: socket_error is returned when the call fails, and 0 is returned when the call times out.

At least one of the three variables readfds, writefds, and limit TFDs is not empty, and the socket group is not empty.
There must be at least one socket. The principle is very simple. Otherwise, what should I do with the SELECT statement. For example, to test whether a socket is readable:

Fd_set fdread;
// Fd_zero Definition
// # Define fd_zero (SET) (fd_set far *) (SET)-> fd_count = 0)
Fd_zero (& fdread );
Fd_set (S, & fdread); // Add a socket. For more information, see winsock2.h.
If (select (0, % fdread, null)> 0
{
// Succeeded
If (fd_isset (S, & fread) // whether fread exists. For details, see winsock2.h.
{
// It is readable.
}
}

◆ I/O operation functions: these functions are mainly used to obtain socket-related operation parameters.

 int  ioctlsocket(SOCKET s, long cmd, u_long FAR * argp );     

S is the socket for I/O operations.
CMD is the socket operation command.
Argp is the pointer to the parameters in the command.

Common commands:

// Determine the amount of data automatically read by the socket
# Define fionread _ ior (''' f''', 127, u_long)/* Get # bytes to read */
// Allow or disable the non-blocking mode of the socket. The value is not 0, and the value is 0.
# Define fionbio _ Iow (''' f''', 126, u_long)/* Set/clear non-blocking I/O */
// Determine whether all out-of-band 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. The application can receive
Windows message-based network event notification. This model is implemented by calling the wsaasynselect function.
Number automatically sets the socket to non-blocking mode, and registers one or more network times with windows, and provides
Window handle used for notifications. When a 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 the socket for Event Notification
Hwnd is the window handle for receiving messages
Wmsg is the message to receive
Levent is a mask that specifies the combination of network events that an application is interested in:

#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/write notifications:

Int nresult = wsaasyncselect (S, hwnd, wmsg, fd_read | fd_write );
If (nresult = socket_error)
{
// Handle errors
}

Cancellation notification:

      int nResult= WSAAsyncSelect(s,hWnd,0,0); 

When the application window hwnd receives a message, the wmsg. wparam parameter identifies the socket and the lparam low-text mark
Network events, the high-text contains the error code.

4. wsaeventselect Model
The wsaeventselect model is similar to the wsaasynselect model, but the main difference is that when a network event occurs
Send to an event object handle instead of a window.

The procedure is 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. It has two working states: signaled and unsent.
(Nonsignaled) and two working modes: manual reset and auto reset ). Not by default
The working status and manual resetting mode of unsent messages.

B. Associate the event object with the socket and register the event at the same time so that the event object's working status never changes
Sent.

      int  WSAEventSelect( SOCKET s,WSAEVENT hEventObject,long lNetworkEvents );  

S is socket
Heventobject is the event object handle just created
The lnetworkevents is a mask and is defined as described above.

C. After I/O processing, set the event object to not-sent

BOOL WSAResetEvent( WSAEVENT hEvent );

Hevent is the event object

True is returned for success, and false is returned for failure.

D. Wait for the network event to trigger the event handle's working status:

DWORD WSAWaitForMultipleEvents( DWORD cEvents,
const WSAEVENT FAR * lphEvents, BOOL fWaitAll,
DWORD dwTimeout, BOOL fAlertable );

Lpevent is the pointer to the event handle Array
Cevent is the number of event handles, and its maximum value is wsa_maximum_wait_events.
Fwaitall specifies the waiting type: true: returned when the lphevent array duplicates all event objects with signals at the same time;
False: any event returns a signal.
Dwtimeout indicates the wait time-out (MS)
Falertable specifies whether to execute the completion routine when the function returns.

When referencing events in the event array, use the return value of wsawaitformultipleevents, minus
The pre-declared value wsa_wait_event_0 is used to obtain the reference value. For example:

nIndex=WSAWaitForMultipleEvents(…);
MyEvent=EventArray[Index- WSA_WAIT_EVENT_0];

E. Determine the network event type:

int WSAEnumNetworkEvents( SOCKET s,
WSAEVENT hEventObject, LPWSANETWORKEVENTS lpNetworkEvents );

S is socket
Heventobject is the event object to be reset
Lpnetworkevents is the code for recording network events and errors. Its structure is defined as follows:

typedef struct _WSANETWORKEVENTS {
long lNetworkEvents;
int iErrorCode[FD_MAX_EVENTS];
} WSANETWORKEVENTS, FAR * LPWSANETWORKEVENTS;

F. Close the event object handle:

BOOL WSACloseEvent(WSAEVENT hEvent);

If the call is successful, true is returned. Otherwise, false is returned.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.