UDP programming based on non-connection
Similarly, when developing UDP-based applications, the main process is as follows:
For non-connected UDP applications in the development process, the service side and the client's operating process is basically the same. Compared to connection-oriented TCP programs, the server has fewer listen and accept functions. As we have said before, the main function of the Listen function is to turn a socket socket descriptor into passive listening mode, and then call accept primarily to wait for the client to connect to the server (with connect). The Connect function can be used not only for streaming sockets but also for datagram sockets. In TCP, the client calls the Connect function to trigger a TCP 3 handshake to the server, to establish a TCP connection, while in UDP the client calls the function to tell the RECVFROM function to be called later. Only accept data from the server indicated in the Connect function, so that the last two parameters can be set to NULL when you call recvfrom later. It is also said that for UDP programming, the client call to connect is optional: If the Connect function is called, recvfrom can omit the last two parameters, and if connect is not called, Recvfrom must indicate where to collect the data.
For UDP programming is in fact mainly in the data processing, and the non-connected UDP programming to send and receive data to use the most functions are recvfrom () and SendTo (), the prototype is as follows:
ssize_t recvfrom (intvoidintstruct sockaddr *from, socklen_t * Fromlen); ssize_t sendto (intconstvoidintstruct sockaddr *to, Socklen_t Tolen);
The recvfrom function is primarily used to receive data from the socket specified by S and store it in the buffer pointed to by BUF. If the from parameter is not NULL, it carries the address information for the message sender, and Fromlen indicates the size of the information sender's address information structure. If the receiving party is not interested in sending the address, set the From and Fromlen to null. return value: Less than 0, error, greater than 0, actual number of bytes received, equals 0, active shutdown on the side.
The sendto function, mainly the data that the BUF points to is sent to the socket descriptor S, Len is the length of the data to be sent, and the to stores the address information to the end, that is, where the data is destined, and the number of bytes that the Tolen takes up to. return value: Less than 0, with an error, greater than 0, the actual number of bytes sent.
We also know that SendTo is available for connection-oriented streaming sockets, which we have mentioned in the TCP development section. Here is a little wordy, if sendto is used for streaming socket programming, the to and Tolen parameters are ignored, and if the connection is not established when the data is sent, the corresponding prompt error is enotconn.
There is no rule here that is not allowed in the TCP program with SendTo, but we generally do not do so, we understand the understanding, unless you have special needs in the development of the project must be used. Bottom line: Remember that sendto and recvfrom can be used for both sending and receiving data in connection-oriented streaming sockets, or for non-connected datagram sockets. SendTo () and recvfrom () are generally used in program development for non-connected datagram sockets.
UDP server-side code, SERVER.CPP
#include <stdlib.h>#include<stdio.h>#include<errno.h>#include<string.h>#include<unistd.h>#include<netdb.h>#include<sys/socket.h>#include<netinet/inch.h>#include<sys/types.h>#include<arpa/inet.h>#defineMax_msg_size 1024intMainintargcChar**argv) { intSkfd,addrlen,ret; structsockaddr_in addr,cltaddr; Charbuf[max_msg_size]={0}; Charsndbuf[max_msg_size]={0}; //Create a datagram socket SKFD if(0> (Skfd=socket (Af_inet,sock_dgram,0)) {perror ("Create Error"); Exit (1); } bzero (&ADDR,sizeof(structsockaddr_in)); Addr.sin_family=af_inet; Addr.sin_addr.s_addr=htonl (Inaddr_any); Addr.sin_port=htons (Atoi (argv[1])); //bind the socket file descriptor SKFD and the local port and address if(0> (Bind (SKFD, (structsockaddr*) &addr,sizeof(structsockaddr_in)))) {Perror ("Bind Error"); Exit (1); } //start sending and receiving data while(1) {ret=recvfrom (Skfd,buf,max_msg_size,0,(structsockaddr*) &cltaddr,&Addrlen); if(Ret <0) {printf ("recv data from%s:%d error!", Inet_ntoa (CLTADDR.SIN_ADDR), Ntohs (Cltaddr.sin_port)); }Else if(ret = =0) {perror ("client has been closing socket!"); }Else{printf ("From %s:%d,%s", Inet_ntoa (CLTADDR.SIN_ADDR), Ntohs (Cltaddr.sin_port), buf); memset (Sndbuf,0, max_msg_size); Switch(buf[0]){ Case 'a': strcpy (Sndbuf,"After u, Lady ..."); Break; Case 'b': strcpy (Sndbuf,"before u, sir ..."); Break; Case 'C': strcpy (Sndbuf,"Can u?"); Break; default: strcpy (Sndbuf,"I dont ' t know what u want!"); } sendto (Skfd,sndbuf,strlen (sndbuf),0,(structsockaddr*) &Cltaddr,addrlen); } memset (BUF,0, max_msg_size); } return 0;}
UDP client code, CLIENT.CPP
#include <stdlib.h>#include<stdio.h>#include<errno.h>#include<string.h>#include<unistd.h>#include<netdb.h>#include<sys/socket.h>#include<netinet/inch.h>#include<sys/types.h>#include<arpa/inet.h>#defineMax_msg_size 1024intMainintargcChar**argv) { intSkfd,ret,len; structsockaddr_in srvaddr; Charbuf[max_msg_size]={0}; Charsndbuf[max_msg_size]={0}; structin_addr addr; //Create a datagram socket SKFD if(0> (Skfd=socket (Af_inet,sock_dgram,0)) {perror ("Create Error"); Exit (1); } if(0= = Inet_aton (argv[1],&addr)) {Perror ("Server addr invalid!"); Exit (1); } bzero (&SRVADDR,sizeof(structsockaddr_in)); Srvaddr.sin_family=af_inet; Srvaddr.sin_addr=addr; Srvaddr.sin_port=htons (Atoi (argv[2])); //our clients only receive data from hosts that are srvaddr from the server address if(0> (Connect (SKFD), (structsockaddr*) &srvaddr,sizeof(structsockaddr_in)))) {Perror ("Connect Error"); Exit (1); } //start sending and receiving data while(1) {memset (Sndbuf,0, max_msg_size); Len=read (0, sndbuf,max_msg_size); RET=sendto (Skfd,sndbuf,strlen (SNDBUF),0,(structsockaddr*) &srvaddr,sizeof(structsockaddr)); if(ret = =Len) {memset (buf,0, max_msg_size); //we already know the server address information, so the last two parameters are nullRet=recvfrom (Skfd,buf,max_msg_size,0, Null,null); if(Ret <0) {perror ("read error from server!"); }Else if(ret = =0) {perror ("server has been closing socket!"); }Else{Buf[ret]=' /'; printf ("From server:%s\n", BUF); } } } return 0;}
Test results:
Our client receives commands entered by the user command line and sends it to the UDP server side, and the server receives different instructions to the client, and the whole process is as shown above.
UDPCLT.C in the sample code I was called Connect, studious children's shoes can be hands-on test ha do not call connect and then the program to pass it.
Reprinted from: http://blog.chinaunix.net/uid-23069658-id-3276167.html
Linux Network programming: A review of program development based on UDP