UDP-based socket Client Server programming

Source: Internet
Author: User
Tags htons

Before we wrote about the client/server model for TCP, we now write client/server mode on UDP.

There are some essential differences between a TCP-written application and a TCP-based application because of the difference between the two transport tiers: UDP is a non-connected, unreliable datagram protocol, unlike the connection-oriented, reliable byte stream provided by TCP.

Let's start with a simple model: in a UDP-based application, the client does not establish a connection to the server, but only uses the SendTo function to send datagrams to the server, where the address of the destination (that is, the server) must be specified as the parameter. Of course, the server side does not accept connections from customers, just use the Recvfrom function to wait for data from a customer to arrive.

Next, let's say two important functions that will be used:

ssize_t recvfrom (int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen);

The first 3 parameters are the socket descriptor we created, pointing to the buffer pointer read in or written out, and the number of read and write bytes;

The 4th parameter is now temporarily assigned a value of 0;

The 5th parameter, SRC_ADDR, points to a socket address structure that will be filled in by the function when the datagram sender's protocol address is returned, and the number of bytes filled in the socket address structure is returned to the caller in the integer specified by the ADDRLRN parameter.

ssize_t sendto (int sockfd, const void *buf, size_t len, int flags,const struct sockaddr *dest_addr, socklen_t Addrlen);

The first three parameters are the same as the recvfrom parameters;

The 4th parameter points to a socket address structure that contains the protocol address (IP address and port number) of the recipient of the packet, and its size is also determined by the 6th parameter.

Note:sendto The last parameter is an integer value, and the last parameter of Recvfrom is a pointer to an integer value (that is, the input output shape parameter). The last two parameters of the recvfrom are similar to the last two parameters of the accept, and the contents of the socket address structure are returned to tell us who sent the datagram (UDP) or who initiated the connection (TCP). The last two parameters of the SendTo are similar to the last two parameters of Connect, where the socket address structure is filled in with the protocol address that the datagram will be sent to (UDP) or connected with (TCP).


Let's look at the code specifically:

Server-side:


  #include  <stdio.h>    #include  <string.h>    #include  <errno.h>    #include <stdlib.h>    #include  <netinet/ in.h>    #include  <arpa/inet.h>    #include  <sys/types.h>     #include  <sys/socket.h>     void usage (const  Char* arg)   {      printf ("%s [ip][port\n", Arg);   }    int main (int argc,char *argv[])   {       if (argc != 3)       {           usage (Argv[0]);           exit (0);       }        int port=atoi (argv[2 ]);    &Nbsp;  char *ip=argv[1];        int sock=socket (AF _inet,sock_dgram,0)///For Datagram       if (sock<0)        {          perror ("socket");           exit (1);      }         struct sockaddr_in local;                                                                                                                                                     local.sin_family=af_inet;      local.sin_port=htons (port);  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOCAL.SIN_ADDR.S_ADDR=INET_ADDR (IP);       Local.sin_port=htons (port);       local.sin_addr.s_addr=inet_addr (IP);         if (Bind (sock, (struct sockaddr*) &local,sizeof (local)) <0)       {          perror ("Bind" );                                                                                                                                                               exit (2);       }        struct  sockaddr_in client;      socklen_t len=sizeof (client);       chaR buf[1024];      while (1)       {           memset (buf, ' + ', sizeof (BUF));           ssize_t _s =recvfrom (sock,buf,sizeof (BUF) -1,0, (struct sockaddr*) &client,&len);           if (_s>0)            {               buf[_s]= ';               printf ("[%s %d]#:%s", Inet_ntoa (CLIENT.SIN_ADDR), Ntohs (Client.sin_port), buf);           }         else  if (_s == 0)           {               printf ("client close...\n");               break;          }           else{//recv fail             }      }       return 0;  }

Take a look at the client:

Void usage (Const char* arg)   {      printf ("%s [ Remote_ip][remote_port\n ", Arg);   }    int main (int argc,char * Argv[])   {      if (argc != 3)        {          usage (argv[0]);           exit (0);      }         int port=atoi (argv[2]);      char *ip=argv[1];                                                                                                                                                                int sock=socket (af_inet,sock_dgram,0);//For Datagram       if (sock<0 )       {          perror (" Socket ");           exit (1);       }        struct sockaddr_in remote;       remote.sin_Family=af_inet;      remote.sin_port=htons (port);      &NBSP;REMOTE.SIN_ADDR.S_ADDR=INET_ADDR (IP);         char buf[1024] ;       while (1)       {           printf ("please enter: ");           fflush (stdout);           ssize_t  _s=read (0,buf,sizeof (BUF)-1);           buf[_s]= ';           _s=sendto (Sock,buf,strlen (BUF), 0, (struct  sockaddr*) &remote,sizeof (remote));      }       return 0;  }

The results of the operation are as follows:

650) this.width=650; "Title=" mxa[(1un3t9rd$08}fjj4sp.png "src=" http://s2.51cto.com/wyfs02/M02/80/F2/ Wkiom1dforyiyeckaabmvgwhlfy714.png "alt=" Wkiom1dforyiyeckaabmvgwhlfy714.png "/>


Test is in the case of a host, we can see the client sends the message received by the server, the implementation of a simple UDP-based communication.

UDP-based socket Client Server 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.