我正在尝试在Windows 7下编写一些代码,以便通过我的本地网络进行广播,并且无法获得以下代码.我来自Linux背景,所以对风格道歉 – 完整的代码编译等工作,如果我使用的地址:
unsigned long broadcastAddr = inet_addr("192.168.10.0") | ~(inet_addr("255.255.240.0"));
然后工作正常,我只是想使用首选的INADDR_BROADCAST / 255.255.255.255方法.
<snip> SOCKET sockfd; int broadcast = 1; WSADATA wsaData; // Windows socket // Initialize Winsock if (WSAStartup(MAKEWORD(2,2),&wsaData) == SOCKET_ERROR) { perror("WinSock Error"); getc(stdin); exit(EXIT_FAILURE); } if ((sockfd = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)) == -1) { perror("Socket Error"); getc(stdin); exit(1); } if ((setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,(char *)&broadcast,sizeof(broadcast))) == SOCKET_ERROR) { perror("Setsockopt - SOL_SOCKET"); getc(stdin); exit(1); } struct sockaddr_in recvaddr; recvaddr.sin_family = AF_INET; recvaddr.sin_port = htons(PORT); recvaddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); memset(recvaddr.sin_zero,'\0',sizeof(recvaddr.sin_zero)); int numbytes = 0; while ((numbytes = sendto(sockfd,greet,strlen(greet),MSG_DONTROUTE,(struct sockaddr *)&recvaddr,sizeof(struct sockaddr_in))) != -1) { printf("Sent a packet %d\n",numbytes); Sleep(100); }
Windows 7中存在一个用于UDP广播的巨大错误,这使得255.255.255.255上的广播无法在大多数Windows 7上安装:
https://serverfault.com/questions/72112/how-to-alter-the-global-broadcast-address-255-255-255-255-behavior-on-windows
基本上它只会在单个网络接口上发送广播,这可能是任何东西,甚至类似于VM网络接口或蓝牙接口,最终可能不会向任何设备广播.