1、服务器ser.c
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <assert.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9
10 //服务器与客户端UDP
11 int main()
12 {
13 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);//套接字
14 assert(sockfd != -1);
15
16 struct sockaddr_in saddr, caddr;
17 memset(&saddr,0, sizeof(saddr));
18 saddr.sin_family = AF_INET;
19 saddr.sin_port = htons(6001);
20 saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
21
22 int res = bind(sockfd, (struct sockaddr*)&saddr, sizeof(saddr));
23 assert(res != -1);
24
25 while(1)
26 {
27 int len = sizeof(caddr);
28 char buff[128] = {0};
29 recvfrom(sockfd,buff, 1,0,(struct sockaddr*)&caddr, &len);//127->1
30 printf("ip=%s,port=%d,buff=%s\n",inet_ntoa(caddr.sin_addr),ntohs(caddr.sin_port),buff);
31
32 sendto(sockfd,"ok", 2, 0,(struct sockaddr*) &caddr,sizeof(caddr));
33 }
34 }
2、客户端cli.c
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <assert.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9
10 //服务器与客户端UDP
11 int main()
12 {
13 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);//套接字
14 assert(sockfd != -1);
15
16 struct sockaddr_in saddr, caddr;
17 memset(&saddr,0, sizeof(saddr));
18 saddr.sin_family = AF_INET;
19 saddr.sin_port = htons(6001);
20 saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
21
22 while(1)
23 {
24 char buff[128] = {0};
25 printf("input:\n");
26
27 fgets(buff,128,stdin);
28 if(strncmp(buff,"end",3) == 0)
29 {
30 break;
31 }
32
33 sendto(sockfd,buff,strlen(buff),0,(struct sockaddr*)&saddr, sizeof(saddr));
34 memset(buff,0,128);
35 int len = sizeof(caddr);
36 recvfrom(sockfd,buff,127,0,(struct sockaddr*)&caddr, &len);
37 printf("buff=%s\n",buff);
38 }
39 close(sockfd);
40 }