套接字编程(UDP)

时间:2022-05-01 18:01:24

UDP是无连接的,不可靠的数据协议报,而TCP是面向连接的,提供可靠的字节流。然而在有些情况下更适合用UDP而不是TCP。有些流行的应用程序是用UDP实现的:DNS(域名系统),NFS(网络文件系统)和SNMP(简单网络管理协议)等

套接字编程(UDP)套接字编程(UDP)
 1 #include<unistd.h>
 2 #include<sys/types.h>
 3 #include<sys/socket.h>
 4 #include<arpa/inet.h>
 5 #include<stdio.h>
 6 #include<errno.h>
 7 #include<stdlib.h>
 8 int main()
 9 {
10     int sockfd=socket(AF_INET,SOCK_DGRAM,0);
11 
12     struct sockaddr_in saddr;
13     saddr.sin_family=AF_INET;
14     saddr.sin_port=htons(7319);
15     inet_pton(AF_INET,"192.168.6.11",&saddr.sin_addr.s_addr);
16 
17     int ret=bind(sockfd,(struct sockaddr *)&saddr,sizeof(saddr));
18     if(ret<0)
19     {
20         perror("bind failed:");
21         exit(0);
22     }
23 
24     char buf[20];
25     char addr[20];
26     struct sockaddr_in caddr;
27     int len=sizeof(caddr);
28     while(1)
29     {
30         ret=recvfrom(sockfd,buf,20,0,(struct sockaddr *)&caddr,&len);
31         if(ret<=0)
32         {
33             printf("recvfrom error:\n");
34             close(sockfd);
35             exit(0);
36         }
37         puts(buf);
38         printf("port:%d addr:%s\n",ntohs(caddr.sin_port),inet_ntop(AF_INET,&
39 caddr.sin_addr.s_addr,addr,20));
40     }
41     close(sockfd);
42     return 0;
43 }
server.c
套接字编程(UDP)套接字编程(UDP)
 1 #include<unistd.h>
 2 #include<stdlib.h>
 3 #include<sys/types.h>
 4 #include<sys/socket.h>
 5 #include<arpa/inet.h>
 6 #include<stdio.h>
 7 #include<errno.h>
 8 #include<string.h>
 9 int main()
10 {
11     int sockfd=socket(AF_INET,SOCK_DGRAM,0);
12     struct sockaddr_in saddr;
13     saddr.sin_family=AF_INET;
14     saddr.sin_port=htons(7319);
15     inet_pton(AF_INET,"192.168.6.11",&saddr.sin_addr.s_addr);
16 
17     char buf[20];
18     int ret;
19     while(1)
20     {
21         printf("请输入buf:");
22         scanf("%s",buf);
23          ret=sendto(sockfd,buf,strlen(buf)+1,0,(struct sockaddr *)&saddr,size
24  of(saddr));
25          printf("ret=%d\n",ret);
26      }
27      close(sockfd);
28      return 0;
29  }
client.c

效果如下:套接字编程(UDP)