码迷,mamicode.com
首页 > 其他好文 > 详细

基于UDP协议的socket通信

时间:2016-05-24 22:50:28      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:基于udp协议的socket通信

UDP提供了无连接通信,且不对传送数据包进行可靠性保证,适合于一次传输少量数据。

具体实现:

udp_server.c

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<errno.h>
  4 #include<sys/types.h>
  5 #include<sys/socket.h>
  6 #include<unistd.h>
  7 #include<string.h>
  8 #include<arpa/inet.h>
  9 #include<netinet/in.h>
 10 void usage(char* argv)
 11 {   
 12     printf("%s:[ip][port]\n",argv);
 13 }
 14 
 15 int main(int argc,char* argv[])
 16 {
 17     if(argc!=3) //判断传参错误
 18     {
 19         usage(argv[0]);
 20         exit(1);
 21     }
 22     int port=atoi(argv[2]);
 23     char* ip=argv[1];
 24     //sock()
 25      int sock=socket(AF_INET,SOCK_DGRAM,0); //创建套接字
 26     if(sock<0)
 27     {
 28         perror("sock");
 29         exit(2);
 30     }
 31     struct sockaddr_in local;
 32     local.sin_family=AF_INET;
 33     local.sin_port=htons(port);
 34     local.sin_addr.s_addr=inet_addr(ip);
 35     if(bind(sock,(struct sockaddr*)&local,sizeof(local))<0)  //绑定本地地址
 36     {
 37         perror("bind\n");                                    //UDP面向无连接的,所以                                                                    无需进行监听,接收
 38         exit(1);
 39     }
 40      struct sockaddr_in client;
 41      socklen_t size=sizeof(client);
 42     char buf[1024];
 43     while(1)
 44     {
 45         size_t _s=recvfrom(sock,buf,sizeof(buf)-1,0,(struct sockaddr*)&clien    t,&size);
 46         if(_s>0)
 47         {
 48             buf[_s-1]=‘\0‘;
 49             printf("[ip]:%s",inet_ntoa(client.sin_addr));
 50             printf("[port]:%ld",ntohs(client.sin_port));
 51             printf("get connection..\n");
 52             printf("%s\n",buf);
 53         }
 54         else if(_s==0)
 55         {
 56             printf("client close\n");
 57         }
 58         else
 59         {
 60             perror("read");
 61         }
 62     }
 63 
 64 
 65     return 0;
 66 }

实现结果:

[admin@www socket]$ ./udp_server 127.0.0.1 8080
[ip]:127.0.0.1[port]:57701get connection..
nihao
[ip]:127.0.0.1[port]:57701get connection..
woaini
^C


本文出自 “liveyoung” 博客,转载请与作者联系!

基于UDP协议的socket通信

标签:基于udp协议的socket通信

原文地址:http://youngyoungla.blog.51cto.com/10697042/1782677

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!