多个UDP监听同一个端口

测试结果:客户端的数据总是发给最后一个打开的服务器

 

服务器代码:socket()->setsockopt()->bind()->recvfrom()/sendto()

 1 #include 
 2 #include 
 3 #include 
 4 #include 
 5 #include in.h>
 6 #include 
 7 #include <string.h>
 8 #include 
 9 
10 
11 int main(int argc, char const *argv[]) {
12     int serverfd;
13     sockaddr_in sadd, cadd;
14     int port = atoi(argv[1]);
15 
16     serverfd = socket(AF_INET, SOCK_DGRAM, 0);
17     int on = 1;
18     setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
19 
20     bzero(&sadd, sizeof(sadd));
21     sadd.sin_family = AF_INET;
22     sadd.sin_addr.s_addr = htonl(INADDR_ANY);
23     sadd.sin_port = htons(port);
24 
25     bind(serverfd, (sockaddr*)&sadd, sizeof(sadd));
26 
27     int i = 0;
28     while(1) {
29         char msg[1024];
30         socklen_t len = sizeof(cadd);
31         int n;
32         n = recvfrom(serverfd, msg, 1024, 0,(sockaddr*)&cadd, &len);
33         printf("%d\n", i++);
34         sendto(serverfd, msg, n, 0, (sockaddr*)&cadd, len);
35     }
36 
37 }

客户端代码:socket()->sendto()/recvfrom()

 1 #include 
 2 #include 
 3 #include 
 4 #include 
 5 #include in.h>
 6 #include 
 7 #include <string.h>
 8 #include 
 9 
10 int main(int argc, char const *argv[])
11 {
12     int fd;
13     sockaddr_in saddr;
14     int port = atoi(argv[1]);
15 
16     fd = socket(AF_INET, SOCK_DGRAM, 0);
17 
18     bzero(&saddr, sizeof(saddr));
19     saddr.sin_family = AF_INET;
20     saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
21     saddr.sin_port = htons(port);
22 
23     while(1) {
24         sleep(atoi(argv[2]));
25         char msg[1024] = "aaaaa";
26         //scanf("%s", msg);
27         socklen_t len = sizeof(saddr);
28         sendto(fd, msg, strlen(msg), 0, (sockaddr*)&saddr, len);
29         int n = recvfrom(fd, msg, 1024, 0, nullptr, nullptr);
30         printf("%s\n", msg);
31     }
32 }

 

转载于:https://www.cnblogs.com/Zzz-y/p/9497231.html

你可能感兴趣的:(多个UDP监听同一个端口)