天天看點

基于UDP協定的socket通信

UDP提供了無連接配接通信,且不對傳送資料包進行可靠性保證,适合于一次傳輸少量資料。

具體實作:

  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      

繼續閱讀