WinSock programming process

Source: Internet
Author: User
Tags htons

I read WinSock programming in "Windows programming" compiled by instructor Wang Yanping. I will sort it out here.

U_short htons (u_short hostshort) // convert the byte sequence of a u_short type from the host to the TCP/IP network byte sequence
U_long htonl (u_long hostlong) // convert a u_long type from the host byte sequence to the TCP/IP network byte sequence
U_short ntohs (u_short netshort) // convert a u_short type from TCP/IP network byte order to host byte order
U_long ntohl (u_long netlong) // convert the byte sequence of a u_long type from TCP/IP network to host byte sequence

 

The general steps for programming with WinSock are OK. You can perform the following steps:

① Load, initialize, and release the WinSock database.

All WinSock functions are exported from the WS2_32.dll library. VC ++ is not connected to this library by default. To use the WinSock API, you must include the corresponding library file.

# Pragma comment (lib, "wsock32.lib ");

WSAstartup must be the WinSock function that the application calls first. It allows the application to specify the version of the required Windows Sockets API and obtain detailed information about the specific WinSock implementation. Only after this function is successfully called can the application call other Winsock APIs.

Int WSAstartup (

WORD wVersionRequested, // The maximum Winsock version supported by the application. The high byte is the minor version number, and the low byte is the major version number.

LPWSADATA lpWSAData); // a pointer to the WSADATA structure, which is used to return the detailed information of the DLL library.

If the function is successfully called, 0 is returned. Otherwise, you must call the WSAGetLastError function to view the cause of the error. This function is equivalent to WIN32 API GetLastError, which obtains the Code with the final error.

Each WSAStartup call must correspond to a WSACleanup call. This function releases the Winsock library.

Int WSACleanup (void ).

② Socket creation and Closure

Before using a socket, you must call the socket function to create a socket object. If this function is successfully called, the socket handle is returned. If the call fails, INVALID_SOCKET (-1) is returned. You can use WSAGetLastError to obtain the error message.

SOCKET socket (

Int af, // specifies the address format used by the socket. In WinSock, only AF_INET is supported.

Int type, // specifies the type of the set of characters, including SOCK_STREAM, SOCK_DGRAM, and SOCK_RAW.

Int protocol); // used with the type parameter to specify the protocol type used, such as IPPROTO_TCP.

When the type parameter is set to SOCK_STREAM or SOCK_DGRAM, the system has explicitly determined to use TCP or UDP protocol for work, so the protocol parameter can be set to 0.

When you do not use a socket to create a socket, you should use the closesocket function to close it. If no error occurs, the function returns 0; otherwise, SOCKET_ERROR is returned. Function usage:

Int closesocket (SOCKET s );

③ Bind the socket to the specified IP address and port number (server)

Bind is used to associate a socket with a local address.

Int bind (

SOCKET s, // SOCKET handle

Const struct sockaddr * name, // local address to be associated

Int namelen); // address Length

The bind function arranges a local name to establish a local association with the Untitled socket.

// Fill in the sockaddr_sin Structure

Sockaddr_in sin;

Sin. sin_family = AF_INET;

Sin. sin_port = htons (8888 );

Sin. sin_addr.S_un.S_addr = INADDR_ANY;

// Bind this character set to a local address

If (: bind (s, (LPSOCKADDR) & sin, sizeof (sin) = SOCKET_ERROR)

{

Printf ("Failed bind () \ n ");

: WSACleanup ();

Return 0;

}

The sin_family field in the sockaddr_in structure is used to specify the address family. This field has the same meaning as the af parameter in the socket function. Therefore, the only available value is AF_INET. The sin_port and sin_addr fields respectively specify the IP address of the port number to be bound to the socket. The data in these two fields must be in the byte sequence of the network. Because the network bytes are in the opposite order of Intel CPU bytes, you must first call the htons function for conversion.

If the application does not care about the address used, you can specify the Internet address as INADDR_ANY (the system automatically uses the IP address configured on the current host ), set the port number to 0 (a unique port number is allocated to this application during program execution, and its value ranges from 1024 to 5000 ). The application can use getsockname after bind to know the address assigned to it. However, it is important to note that getsockname can be used to enter the Internet address after the socket connection is established, because multiple addresses may be available for a host.

④ Set the socket to enter the listening status (server)

The listen function sets the socket to enter the listening status.

Int listen (

SOCKET s, // SOCKET handle

Int backlog); // The maximum number of unprocessed connections that are allowed to be preserved in the listener column.

To accept the connection, use the socket function to create a socket, bind it to a local address using the bing function, and then use the listen function to specify a backlog for the connection, finally, use accept to accept the request connection.

The listen function is only used on sockets that support connections, such as SOCK_STREAM. After the function is successfully executed, socket s enters the passive mode, and the incoming connection will be notified, waiting in queue for processing.

Servers that process multiple connection requests within the same time usually use the listen function: If a connection request arrives and the queue is full, the client will receive the WSAECONNREFUSED error.

⑤ Accept connection (server)

The accept function is used to receive incoming requests.

SOCKET accept (

SOCKET s, // SOCKET handle

Struct sockaddr * addr, // a pointer to the sockaddr structure, used to obtain the address information of the other party

Int * addrlen); // a pointer to the address length.

This function extracts the first connection in the unprocessed connection on s, creates a new socket for the connection, and returns its handle. The newly created socket is the socket that processes the actual connection. It has the same attributes as s.

The program works in blocking mode by default. In this mode, if no unprocessed connection exists, the accept function will wait until a new connection exists.

The addrlen parameter is used to specify the size of the Space indicated by addr, and return the actual length of the returned address. If addr or addrlen is NULL, no remote address information is returned.

⑥ Request connection (client)

After the client creates a socket, it must use the connect function request to connect to the server. The function prototype is as follows.

Int connect (

SOCKET s, // SOCKET handle

Const struct sockaddr FAR * name, // pointer to the sockaddr structure, containing the address information of the server to be connected

Int namelen); // length of the sockaddr Structure

The first parameter is the client socket used by the connection. The other two parameters are used to address remote sockets.

7. send and receive data

For a streaming socket, The send and recv functions are generally used to send and receive data.

Int send (

SOCKET s, // SOCKET handle

Const char FAR * buf, // The buffer address of the data to be sent

Int len, // buffer Length

Int flags); // specifies the call method, usually set to 0

Int recv (

SOCKET s, // SOCKET handle

Char FAR * buf, // buffer address for receiving data

Int len, // buffer Length

Int flags); // specifies the call method, usually set to 0

The send function sends data in the buffer zone on a connected socket and returns the actual bytes of the data. The recv function accepts data from the other party and stores the data in the specified buffer zone. The flags parameter is usually set to 0 in these two functions.

In blocking mode, sending will block thread execution until all data is sent (or an error occurs), and The recv function will return as many currently available information as possible, until the specified buffer size.

Related Article

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.