Server programs and client programs for UDP

Source: Internet
Author: User
Server program: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> # 
Include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #define PORT 8082 #define BUFSIZE 512
Char buf[bufsize+1];
   int main () {//step 1th creates socket int sockfd=socket (af_inet,sock_dgram,0);
   The 2nd step is to set the address structure body struct sockaddr_in svraddr;
   svraddr.sin_family=af_inet;//uses Internet Protocol svraddr.sin_port=htons (port);
   Inet_aton ("0.0.0.0", &svraddr.sin_addr);
   Step 3rd Binding int Ret=bind (SOCKFD, (struct sockaddr*) &svraddr,sizeof (SVRADDR));
   if (ret<0) {printf ("Cannot bind!\r\n"); exit (-1);
               while (1) {struct sockaddr_in cli;
       int len=sizeof (CLI);
       int Z=recvfrom (sockfd,buf,bufsize,0, (struct sockaddr*) &cli,&len);//6th step read Socket buf[z]= ' ""; printf ("%s\r\n", buf);//print}//client program CLI.C//from http://www.bianceng.cn #include <stdio.h> #include ; stdlib.h> #include <string.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h>
#include <unistd.h> #define PORT 8082 #define BufSize Char buf[bufsize+1];
   int main () {//step 1th creates an individual socket int sockfd=socket (af_inet,sock_dgram,0);
   The 2nd step is to set up the addr structure body struct sockaddr_in svraddr;
   svraddr.sin_family=af_inet;//uses Internet Protocol svraddr.sin_port=htons (port);
   Inet_aton ("127.0.0.1", &svraddr.sin_addr);
   The 3rd step connects the server//connect (SOCKFD, (struct sockaddr*) &svraddr,sizeof (SVRADDR));
   while (1) {scanf ("%s", buf); SendTo (Sockfd,buf,strlen (BUF), 0, (struct sockaddr*) &svraddr,sizeof (SVRADDR)); Step 4th writes the string to a socket}}

This article from the "Live Well" blog, please be sure to keep this source http://wolfword.blog.51cto.com/4892126/1224934

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Servers/zs/

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.