Mfc--10. Fundamentals of Network programming

Source: Internet
Author: User
Tags terminates server port htons

LESSON10: Fundamentals of Network programming

Network programming is an important branch of computer programming, is the basis of network communication, network programming is mainly used in the Windows system system provides socket. Network communication is also divided into TCP-based and UDP-based two kinds. This paper mainly explains the basic knowledge of network programming based on TCP and UDP.

1. TCP-based socket programming
1.1 TCP Server

#include <winsock2.h> #include <stdio.h>//#include <iostream> #pragma comment (lib, "Ws2_32.lib")//Static         State to add a Lib file, which is the library file Ws2_32.lib file, which provides support for the following network-related APIs void Main () {/******** first sets the communication version **************/         wordwversionrequested;         Wsadatawsadata;          Interr;     Wversionrequested= Makeword (1, 1);      The requested communication version is (err=) WSAStartup (wversionrequested, &wsadata);     Call the WSAStartup function if (err! = 0) return; If the return value is not 0, it indicates that there is no corresponding winsockdll. returns if (Lobyte (wsadata.wversion)! = 1 | |     Hibyte (wsadata.wversion)! = 1) {wsacleanup ();                                   If the high byte of the version is not 1 and the low byte is not 1, it is returned.         Return           }//1 Create Socket SOCKETSOCKSRV = socket (af_inet, sock_stream,0); (1 Address family af_inet or pf_inet,2socket type Sock_stream or sock_dgram,3 associated with a particular address family) call to successfully return a socket descriptor for the new socket data type//        2 bind socket to local address and port/*structsockaddr_in{           Short sin_family;        Address family Unsignedshort Sin_port;      Port number struct IN_ADDR sin_addr;      Host IP address of socket char sin_zero[8];         Padding number, make sockaddr_in and sockaddr structure length same}*/sockaddr_inaddrsrv; Addrsrv.sin_addr. S_un.          S_addr= htonl (Inaddr_any); Call the HTONL function to convert the host byte order to TCP/IP network byte order//addrsrv is a struct with a struct variable sin_addr that contains a shared body s_un and then a shared member s_addr,inet_         The addr function converts the host byte order to the network byte order addrsrv.sin_family= af_inet;             Addrsrv.sin_port=htons (6000); Port number 6000, requires more than 1024 port number, network byte order, need to convert, htonl and htons different is the range of conversion data bind (Socksrv, (sockaddr*) &addrsrv,sizeof (sockaddr))        ;         A function that binds sockets and addresses (1 specifies the socket to bind, 2 the local address information for the socket, a pointer variable pointing to the SOCKADDR structure, 3 specifies the length of the address)//3 calls the Listen function, sets the socket to listening mode, prepares to accept customer requests       Listen (socksrv,5);                 (Socket descriptor, maximum number of waiting connections)//4 waits for a client request to arrive//5 to communicate with the returned socket and client//6 return, waiting for another client to request//7 close socket Sockaddr_inaddrClient;         A variable that defines an address structure used to accept the address information of the client, using Intlen = sizeof (SOCKADDR) in the loop structure; while (1)//dead loop, always listening, continuous operation {socketsockconn=accept (socksrv, (sockaddr*) &addrclie            Nt,&len); (1 the host server socket descriptor is in the listening state, 2 points to the buffer pointer connection entity address, holds the IP information and port information of the originating client, 3 points to the integer pointer, contains the length of the return address structure), returns a new connected socket descriptor, communicates with him and the client, Previous sockets continue to listen for client connection requests//Send data/*intsend (socket                            s,//set the socket descriptor corresponding to the connection, not the listener socket constchar FAR * buf,//A buff pointer containing the data to be transferred                            int len, length of data in//buffer intflags//Set call behavior for Send                   ); */charsendbuf[100];    sprintf_s (SendBuf, "welcome%s to Http://www.sunxin.org", Inet_ntoa (ADDRCLIENT.SIN_ADDR));                   Writes formatted data to a string, sending the client address to the%s in the string, send (Sockconn,sendbuf, strlen (sendbuf) +1, 0); Accepts data/*intrecv (the Windows socketsrecv function receives data from a connected socket.                             SOCKETs,//establish a connected socket charfar* BUF,//Receive data buff Intlen, length of//buff intflags//Set Accept function                   Call behavior); */charrecvbuf[100];                   Recv (Sockconn,recvbuf, strlen (recvbuf) + 1, 0);                   printf ("%s\n", recvbuf);         Closesocket (Sockconn); }}

1.2 TCP Client

#include <winsock2.h> #include <stdio.h>//#include <iostream> #pragma comment (lib, "Ws2_32.lib")         void Main () {/******** first sets the communication version **************/wordwversionrequested;         Wsadatawsadata;          Interr;      Wversionrequested= Makeword (1, 1);  The requested communication version is (err=) WSAStartup (wversionrequested, &wsadata);            Call the WSAStartup function if (err! = 0) return; If the return value is not 0, it indicates that there is no corresponding winsockdll. returns if (Lobyte (wsadata.wversion)! = 1 | |     Hibyte (wsadata.wversion)! = 1) {wsacleanup ();                                   If the high byte of the version is not 1 and the low byte is not 1, it is returned.         Return           }//1 Create socket socketsockclient= socket (af_inet, sock_stream, 0); (1 Address family af_inet or pf_inet,2socket type Sock_stream or sock_dgram,3 associated with a particular address family) call to successfully return a socket descriptor for the new socket data type/*intconn     ECT (//the Windows socketsconnect function establishes a connection to a specifed socket.              SOCKETs,//socket conststruct sockaddr far* name,//Address struct pointer, used to set the link server address information Intnamelen//address structure length); */                           /2 connection server sockaddr_inaddrsrv; Sockaddr_in is a struct variable addrsrv.sin_addr. S_un.       S_addr= inet_addr ("127.0.0.1"); Addrsrv is a struct with a struct variable sin_addr that contains a common body s_un, and then a shared body member S_addr,inet_addr function to convert the host byte order to the network byte order addrsrv.sin_family= af_         INET;    addrsrv.sin_port= htons (6000);          Host byte-order conversion to network byte-order connect (sockclient, (sockaddr*) &addrsrv,sizeof (sockaddr));         3 and the server port to communicate (accept the information sent by the server) charrecvbuf[100];         Recv (Sockclient,recvbuf, strlen (recvbuf) + 1, 0);         printf ("%s\n", recvbuf);          Send (Sockclient, "This was Zhangsan", strlen ("This is Zhangsan") + 1, 0);         4 Close Socket closesocket (sockclient);                WSACleanup (); Terminates the use of the Socket font system ("pAuse "); To prevent Flash back}

2. UDP-based socket programming2.1 UDP Server

#include <winsock2.h> #include <stdio.h> #pragma comment (lib, "Ws2_32.lib") void Main () {/********         First set the communication version **************/wordwversionrequested;         Wsadatawsadata;          Interr;            Wversionrequested= Makeword (1, 1);      The requested communication version is (err=) WSAStartup (wversionrequested, &wsadata);        Call the WSAStartup function if (err! = 0) return; If the return value is not 0, it indicates that there is no corresponding winsockdll. returns if (Lobyte (wsadata.wversion)! = 1 | |      Hibyte (wsadata.wversion)! = 1) {wsacleanup ();                                   If the high byte of the version is not 1 and the low byte is not 1, it is returned.         Return      }//1 Create Socket SOCKETSOCKSRV = socket (af_inet, SOCK_DGRAM, 0); (1 Address family af_inet or pf_inet,2socket type Sock_stream or sock_dgram,3 associated with a particular address family) call successfully returned socket descriptor for the new socket data type//2 bound socket to         Local address and Port Sockaddr_inaddrsrv; Addrsrv.sin_addr. S_un.       S_addr= htonl (Inaddr_any); Call the HTONL function to convert the host byte order to a TCP/IP networkbyte order addrsrv.sin_family= af_inet;              addrsrv.sin_port= htons (6000); The port number is 6000,1024 with the upper port number, requires a network byte order, needs to be converted, htonl and htons differ in the range of conversion data bind (Socksrv, (sockaddr*) &addrsrv, sizeof (SOCKADDR))     ; The Binding function (1 specifies the socket to bind, 2 the local address information for the socket, a pointer variable pointing to the SOCKADDR structure, and 3 specifies the length of the address)/*intrecvfrom (the Windows Socketsrec                   Vfrom function receives a datagram and stores the source address. SOCKETs,//Socket charfar* buf,//buffer int len receiving data,//b Uffer length int flags,//Set Recvfrom function call behavior structsockaddr far* from,//address struct pointer, receive send number          Address information intfar* Fromlen//function return value, return the size of the address structure); *///3 waiting to receive data recvfrom     Sockaddr_inaddrclient;         A variable that defines an address structure used to accept the address information of the client, using Intlen = sizeof (SOCKADDR) in the loop structure;          CHARRECVBUF[100]; Recvfrom (Socksrv,recvbuf, strlen (recvbuf) + 1, 0, (sockaddr*) &addrcliENT, &len);          printf ("%s\n", recvbuf);         4 Close Socket closesocket (SOCKSRV);                     WSACleanup ();                   Terminates the use of the Socket font system ("pause"); To prevent Flash back}

2.2 UDP Client

#include <winsock2.h> #include <stdio.h> #pragma comment (lib, "Ws2_32.lib") void Main () {/********         First set the communication version **************/wordwversionrequested;         Wsadatawsadata;          Interr;         Wversionrequested= Makeword (1, 1);    The requested communication version is (err=) WSAStartup (wversionrequested, &wsadata);          Call the WSAStartup function if (err! = 0) return; If the return value is not 0, it indicates that there is no corresponding winsockdll. returns if (Lobyte (wsadata.wversion)! = 1 | |     Hibyte (wsadata.wversion)! = 1) {wsacleanup ();                                   If the high byte of the version is not 1 and the low byte is not 1, it is returned.         Return           }//1 Create Socket socketsockclient = socket (af_inet, SOCK_DGRAM, 0); (1 Address family af_inet or pf_inet,2socket type Sock_stream or sock_dgram,3 associated with a particular address family) call to successfully return a socket descriptor for the new socket data type/*intsend                   To (the Windows Sockets sendtofunction sends data to a specific destination.                   SOCKETs, Socket Constchar FAR * buf,//contains data to be sent int len,//Length of data Intflags,//Set SendTo function call behavior conststruct sockaddr FAR * to,//address struct pointer, set Address information of the destination socket Inttolen//The length of the address structure); *///2 send data to the server (send         To) Sockaddr_inaddrsrv; Addrsrv.sin_addr. S_un.         S_addr= inet_addr ("127.0.0.1");         Addrsrv.sin_family= af_inet;          addrsrv.sin_port= htons (6000);          SendTo (sockclient, "Hello", strlen ("Hello") + 1, 0, (sockaddr*) &addrsrv,sizeof (sockaddr));         3 Close Socket closesocket (sockclient);           WSACleanup ();          Terminates the use of the Socket font system ("pause"); To prevent Flash back}

Mfc--10. Fundamentals of Network programming

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.