Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

c - UDP Broadcast in Windows 7 - does it work?

I'm trying to write some code under Windows 7 to broadcast across my local network and can't get the following code to work. I come from a Linux background so apologies for style - the full code compiles etc and works and if I use an address of:

unsigned long broadcastAddr = inet_addr("192.168.10.0") | ~(inet_addr("255.255.240.0"));

Then that works fine, I just would really like to use the preferred INADDR_BROADCAST/255.255.255.255 method.

<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,'', 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
", numbytes);
        Sleep(100);
}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a huge bug in Windows 7 for UDP broadcast which makes broadcasting on 255.255.255.255 not work on most windows 7 install: https://serverfault.com/questions/72112/how-to-alter-the-global-broadcast-address-255-255-255-255-behavior-on-windows

Basically it will send the broadcast only on a single network interface, which could be anything, even something like a VM network interface or bluetooth one, which can end up not broadcasting to any device.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...