Linux下UDP收/发广播消息简单实现
发送广播消息
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<sys/types.h> 5 #include<sys/socket.h> 6 #include<sys/wait.h> 7 #include<netinet/in.h> 8 #include<arpa/inet.h> 9 #include <errno.h> 10 11 int main(void) 12 { 13 char rgMessage[128] = "I am sending message to you!"; 14 int iFd; 15 int iSendbytes; 16 int iOptval = 1; 17 struct sockaddr_in Addr; 18 if ((iFd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 19 { 20 printf("socket fail\n"); 21 return -1; 22 } 23 24 if (setsockopt(iFd, SOL_SOCKET, SO_BROADCAST | SO_REUSEADDR, &iOptval, sizeof(int)) < 0) 25 { 26 printf("setsockopt failed!"); 27 } 28 memset(&Addr, 0, sizeof(struct sockaddr_in)); 29 Addr.sin_family = AF_INET; 30 Addr.sin_addr.s_addr = inet_addr("255.255.255.255"); 31 Addr.sin_port = htons(8899); 32 33 while (1) 34 { 35 if ((iSendbytes = sendto(iFd, rgMessage, strlen(rgMessage), 0, (struct sockaddr*)&Addr, sizeof(struct sockaddr))) == -1) 36 { 37 printf("sendto fail, errno=%d\n", errno); 38 return -1; 39 } 40 printf("rgMessage=%s, rgMessageLen=%d,iSendbytes=%d\n", rgMessage, strlen(rgMessage), iSendbytes); 41 sleep(1); 42 } 43 close(iFd); 44 45 return 0; 46 }
接收广播消息
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <sys/socket.h> 5 #include <netinet/in.h> 6 #include <arpa/inet.h> 7 #include <netdb.h> 8 9 int main(void) { 10 11 int iAddrLength; 12 char rgMessage[2014]; 13 int iOptval = 1; 14 int iFd; 15 struct sockaddr_in Addr; 16 17 if ((iFd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 18 { 19 printf("socket fail\n"); 20 return -1; 21 } 22 23 if (setsockopt(iFd, SOL_SOCKET, SO_REUSEADDR, &iOptval, sizeof(int)) < 0) 24 { 25 printf("setsockopt failed!\n"); 26 } 27 memset(&Addr, 0, sizeof(struct sockaddr_in)); 28 Addr.sin_family = AF_INET; 29 Addr.sin_addr.s_addr = INADDR_ANY; 30 Addr.sin_port = htons(8899); 31 iAddrLength = sizeof(Addr); 32 33 if (bind(iFd, (struct sockaddr *)&Addr, sizeof(Addr)) == -1) 34 { 35 printf("bind failed!\n"); 36 } 37 38 while (1) 39 { 40 if (recvfrom(iFd, rgMessage, sizeof(rgMessage), 0, (struct sockaddr *)&Addr, &iAddrLength) == -1) 41 { 42 printf("recv failed!\n"); 43 } 44 printf("recv:%s\n", rgMessage); 45 } 46 47 close(iFd); 48 49 return 0; 50 }