Winsockpragramming (1) Server (c + + edition)

Source: Internet
Author: User
Tags htons

Pre-Preparation:
Connect the dynamic link library Ws2_32.dll in the VC (all Winsock functions are exported from this library). Practice: "Project"-"set"-"Object/Library module", add "Ws2_32.dll".

Create a server process
1, initialize the socket font
Call function WSAStartup (), function prototype:

int WSAStartup (WORD wversionrequested,lpwsadata lpwsadata);

The function call returned successfully to 0.

The parameter wversionrequested represents the version number of the current socket library.

WORD Wversionrequested=makeword (2,0);

Indicates a version number of 2.0
The parameter Lpwsadata is a pointer variable that points to the struct wsadata, which represents the details of the acquired socket font.
Wsadata Structure Definition prototype:

typedef struct wsadata{
WORD wversion;//Library file recommends using a socket version with a program
The highest version supported by the WORD whighversion;//library file
Char szdescription[wsadescription_len+1];//string describing the library file
Char szsystemstatus[wsasys_status_len+1];//System Status String
Unsigned short imaxsockets;//maximum number of sockets supported simultaneously
unsigned short IMAXUDPDG;
char FAR * LPVENDORINFO;
}

Initialize the socket font code:

data;//定义WSAData变量WOED wVersionRequested=MAKEWORD(2,0);//定义套接字库版本号::WSAStartup(wVersionRequested,&data);//初始化套接字库

2. Create socket handle
Call function socket (), function prototype:

Socket socket (int af,int type,int protocol);

parameter AF Specifies the address format used by the socket
parameter type specifies socket type

Sock_stream creating a streaming socket (based on TCP)
Sock_dgram Creating datagram Sockets (UDP-based)
Sock_raw creating the original socket

parameter protocol: If the parameter type has specified that the socket type is TCP or UDP, the parameter can be set to 0.

To create a socket handle code:

SOCKET s;//定义套接字句柄s=::socket(AF_INET,SOCK_STREAM,0);//创建并返回套接字句柄

3. Address structure setting and byte order conversion
At this point we must understand two concepts: the addressing Method and the byte order .
addressing: sockets are used in a variety of protocols, so in order to differentiate the network protocol, it is necessary to set the addressing mode. The IP address and port number are used in the TCP/IP address to determine the communication sides.
Socket address structure Definition:

struct sockaddr_in{
Short sin_family;//Specifies the address family (set to Af_inet to indicate that the app is using TCP/IP)
unsigned short sin_port;//specifying port number
struct IN_ADDR SIN_ADDR;//IP Address
Char sin_zero[8];//reserved, need to be specified as 0
};

The sin_addr represents a 32-bit IP address structure, defined as follows:

struct in_addr{
union{
struct{
unsigned char s_b1,s_b2,s_b3,s_b4;
}s_un_b;//describes IP addresses with 4 U_char characters
struct{
unsigned short s_w1,s_w2;
}s_un_w;//description of IP address with two u_short types
Unsigned long s_addr;//describes IP addresses with a u_long type
}s_un;
};

Typically we use 1 U_long type characters to describe an IP address.

Sockaddr_in addr;
Addr.sin_addr. S_un. S_ADDR=INET_ADDR ("210.6.132.5");

byte order
In socket programming, the order in which data is transmitted is based on network byte order and host byte order. The host sends data to the network, it needs to convert the host byte data into the network byte order; When the host receives the data from the network, it needs to convert the network byte order into the host byte order. From the data storage perspective, the network byte order stores the most important bytes first, while the host byte order stores the unimportant bytes first.

byte order conversion functions are used when byte-order conversions are performed

U_short htons (u_short hostshort);//Convert a U_short type IP address from host byte order to network byte order
U_long htonl (U_long hostlong);//Convert a U_long type IP address from host byte order to network byte order
U_long Ntohl (U_long netlong);//Convert a U_long type IP address from network byte order to host byte order
U_short Ntohs (u_short netshort);//Convert a U_short type IP address from network byte order to host byte order
unsigned long inet_addr (const char FAR*CP);//Convert a string IP to IP in network byte order
Char Far*inet_ntoa (struct in_addr in);//An IP address in network byte order is converted into a string IP

Address structure settings and byte order conversion code:

sockaddr_in addr;//定义套接字地址结构变量in_addr in_add;//定义IP地址结构变量addr.sin_fimily=AF_INET;//指定地址家族为TCP/IPaddr.sin_port=htons(80);//指定端口号addr.sin_addr.S_un.S_addr=inet_addr(‘127.0.0.1‘);//将字符串IP转换为网络字节顺序排列的IPchar address[]=inet_ntoa(addr.sin_addr.S_un.S_addr)//将网络字节顺序排列的IP转换为字符串IP

4. Binding Address Information
Call the bind () function, its function prototype:

int bind (SOCKET s,const struct sockaddr far* name,int namelen);

A function call returns 0 if it succeeds.

Binding Address Information Code:

::bind(s,(sockaddr)&addr,sizeof(addr));

5. Listening sockets (for streaming sockets only)
Call the Listen () function, whose prototype is:

int Listen (SOCKET s,int backlog);

The parameter backlog Specifies the maximum number of connections to listen on.

Listen for Socket code:

::listen(s,5);//在套接字上监听,并且指定最大连接数为5.

6. Receiving Client connection requests
The client calls the Connect () function to send a connection request, and the server calls accept () to receive the request. Accept () function prototype:

Socket accept (Socket s,struct sockaddr far* addr,int far* addrlen);

Receive Client connection request code:

s1=::accept(s,(sockaddr*)&addr,&n);//接受连接请求

7. Data sending and receiving
Call the Send () function and the recv () function, prototype:

int Send (SOCKET s,const char far *buf,int len,int flags);
int recv (SOCKET s,char far *buf,int len,int flags)
The parameter buf is a pointer variable to the data buffer, and the parameter flags is usually set to 0.

Data sending and receiving code:

::send(s1,sztext,sizeof(sztext),0);::recv(s,sztext,sizeof(sztext),0);

8. Close the socket.

Close Socket Code

::closesocket(s);

9. Release Socket font

Release Socket font

::WSACleanup();

Full Source:

/*server.cpp*/#include <winsock2.h>//Include header files #include <stdio.h>#include <windows.h>#pragma comment (lib, "Ws2_32.lib")//Explicit connection socket font intMain () {//Initialize socket fontWsadata data;//wsadata Structure ObjectWORD W=makeword (2,0);//define version number:: WSAStartup (W,&data);//Initialize socket font    Charsztext[]="welcome you \ r \ n";//define and initialize the character array sent to the client    //Create socket handleSOCKET s,s1;//define connection sockets and data receiver socket handlesS=::socket (Af_inet,sock_stream,0);//Create a TCP socket    //Address structure settings and byte conversionSockaddr_in ADDR,ADDR2;//Define socket address structure    intn=sizeof(ADDR2);//Get socket address structure sizeAddr.sin_family=af_inet;//Initialize address structureAddr.sin_port=htons ( the);//Set port numberAddr.sin_addr. S_un. S_addr=inaddr_any;//Bound sockets:: Bind (S, (sockaddr*) &addr,sizeof(addr));//Listener sockets:: Listen (S,5);printf("Server has started \ r \ n");//Output prompt information     while(true){//Accept connection RequestS1=::accept (S, (sockaddr*) &addr2,&n);if(S1!=null) {printf("%s is already connected \ r \ n", Inet_ntoa (ADDR2.SIN_ADDR));//Send a character array to the client:: Send (S1,sztext,sizeof(Sztext),0); }//close socket handle:: Closesocket (s); :: Closesocket (S1);//Release socket font:: WSACleanup ();if(GetChar ()) {return 0; }Else{:: Sleep ( -);//Apply hibernation for 0.1 seconds}    }}

Winsockpragramming (1) Server (c + + edition)

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.