Windows Network Programming

Source: Internet
Author: User

The steps for compiling a network application server using winsock are described as follows:
WSAStartup initialize the network programming library
Create socket
Bind the specified address and port and bind the socket
Listen enters the listening status
Accept waiting to receive new connections
Send/recv send and receive data
Closesocket key socket
WSAStartup releases the use of dynamic libraries

The following describes the APIs in detail.
1.WinsockInitialization
Call the int WSAStartup (WORD wVersionRequested, LPWSADATA lpWSAData) Function
WSAStartup is the startup command of WSA (Windows SocKNDs Asynchronous, Windows Asynchronous socket. It is a command in Windows Network Programming Interface Software Winsock1 or Winsock2 (Ps: Winsock is developed from BSD Socket in Unix and is a programming interface unrelated to network protocols ).
To call any Winsock API function in an application, you must use the WSAStartup function to initialize the Winsock service. Therefore, you must call the WSAStartup function. The program using the Socket must call the WSAStartup function before using the Socket.

WORD wVersionRequested;
WSADATA wsaData;
WVersionRequested = MAKEWORD (2, 2 );

If (WSAStartup (wVersionRequested, & wsaData )! = 0)
{

// Initialization failed

}

If (wsaData. wVersion! = WVersionRequested)
{

// Version mismatch

}

2.Create socket

Int socket (int domain, int type, int protocol );
Function Description:
The first parameter specifies the protocol family used by the application. For the TCP/IP protocol family, this parameter is set to AF_INET;
The second parameter specifies the socket type to be created. The stream socket type is SOCK_STREAM, the datagram socket type is SOCK_DGRAM, and the original socket SOCK_RAW (the WinSock interface does not use a specific protocol to encapsulate it, the program processes the data packets and the protocol header );
The third parameter specifies the communication protocol used by the application. This parameter can specify different transmission protocols in a single protocol series. In the Internet communication domain, this parameter is generally set to 0. The system determines the transport layer protocol to be used based on the socket type.
Returned value: the socket descriptor is returned. Otherwise, the INVALID_SOCKET is returned.

Example:
If (m_sk = socket (AF_INET, SOCK_STREAM, 0) = INVALID_SOCKET)
{

// Failed to create socket

}

3.Bind socket

Definition of address structure:

/*

* Socket address, internet style.

*/
Struct sockaddr_in {
Short sin_family; // protocol family
U_short sin_port; // port number
Struct in_addr sin_addr; // address information
Char sin_zero [8];
};

/*
* Internet address (old style... shoshould be updated)
*/
Struct in_addr {
Union {
Struct {u_char s_b1, s_b2, s_b3, s_b4;} S_un_ B;
Struct {u_short s_w1, s_w2;} S_un_w;
U_long S_addr;
} S_un;

# Define s_addr S_un.S_addr

/* Can be used for most tcp & ip code */

/*

* Structure used by kernel to store most

* Addresses.

*/

Struct sockaddr {

U_short sa_family;/* address family */

Char sa_data [14];/* up to 14 bytes of direct address */

};

Note: s_addr is a macro that allows you to easily set the address.

# Define s_addr S_un.S_addr
/* Can be used for most tcp & ip code */
/*
* Structure used by kernel to store most
* Addresses.
*/
Struct sockaddr {
U_short sa_family;/* address family */
Char sa_data [14];/* up to 14 bytes of direct address */
};
Note: s_addr is a macro that allows you to easily set the address.
The above definition is in winsock2.h.
Bind a function prototype:
Int bind (int sockfd, const struct sockaddr * my_addr, socklen_t addrlen );
Function Description:
In the parameter list, sockfd indicates the socket number (descriptor) that has been created );
My_addr is a pointer to the sockaddr struct type;
The addrlen parameter indicates the length of the my_addr structure, which can be obtained using the sizeof function.

Example:
Sockaddr_in addr;
Addr. sin_family = AF_INET; // use the Internet protocol, that is, the IP protocol.
Addr. sin_port = htons (port );
Addr. sin_addr.S_un.S_addr = htonl (INADDR_ANY );
The IP address parameter is INADDR_ANY, which is automatically specified by the system kernel.
If the port is 0, the system automatically assigns a 1024 ~ Unique port number between 5000

If (bind (m_sk, (sockaddr *) & addr, sizeof (addr) = SOCKET_ERROR)
{
// Binding Error
}

4.Enter listening status

Int listen (int s, int backlog );
Function Description:
S: bound socket
Backlog: Maximum number of connections simultaneously processed
Listen () does not start to receive connections, but sets the socket to the listen mode. The accept () is used to receive connections from the client (). generally, listen () is called after socket () and bind (), and then accept () is called ().

5.Accept connection

Int accept (int s, struct sockaddr * addr, int * addrlen );
When there is a new connection, accept returns a new socket descriptor. The connection request information is stored in addr.
Parameter sockfd
The sockfd parameter is a listening socket. This socket is used to listen to a port. When a customer connects to the server, it uses this port number, which is associated with this socket. Of course, the customer does not know the socket details. It only knows one address and one port number.
Parameter addr
This is a result parameter, which is used to accept a return value. This return value specifies the client address. Of course, this address is described through an address structure. You should know what kind of address structure this address structure is. If you are not interested in the customer's address, you can set this value to NULL.
Parameter len
It is also the result parameter used to accept the size of the above addr structure, which indicates the number of bytes occupied by the addr structure. Similarly, it can be set to NULL.

If accept is returned successfully, the server has established a correct connection with the customer. At this time, the server completes communication with the customer through the socket returned by accept.

6.Send and receive data

Int send (int s, const void * buf, int len, int flags );
Int recv (int s, void * buf, int len, int flags );
The function returns the number of bytes actually sent and received. Error-1 returned. You need to disable this connection.
By default, the function is blocked until the sending/receiving process is complete.
Note: If the return value of the send function is not the same as the len parameter, the remaining unsent information needs to be sent again.
After the recv receives the data, it does not add '\ 0' to the end '.

7.Other APIs

WSAGetLastError ()
Returns the error status of the last failed operation.
Closesocket (int socket)
Disable socket
WSACleanup ()
Terminate the use of Winsock 2 DLL (Ws2_32.dll)

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.