1. 程式人生 > >多個UDP監聽同一個端口

多個UDP監聽同一個端口

sys any cad %s clu htons 監聽 nbsp pre

測試結果:客戶端的數據總是發給最後一個打開的服務器

服務器代碼:socket()->setsockopt()->bind()->recvfrom()/sendto()

 1 #include <stdio.h>
 2 #include <sys/socket.h>
 3 #include <sys/types.h>
 4 #include <arpa/inet.h>
 5 #include <netinet/in.h>
 6 #include <unistd.h>
 7 #include <string
.h> 8 #include <stdlib.h> 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 <stdio.h>
 2 #include <sys/socket.h>
 3 #include <sys/types.h>
 4 #include <arpa/inet.h>
 5 #include <netinet/in.h>
 6 #include <unistd.h>
 7 #include <string.h>
 8 #include <stdlib.h>
 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 }

多個UDP監聽同一個端口