UDP Broadcast on Windows 7 - Does It Work?

I am trying to write code under Windows 7 for broadcast over a local network and cannot get the following code to work. I came from the Linux background, so I apologize for the style - the full code compiles, etc. And it works, and if I use the address:

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

Then it works well, I just would like to use the preferred method 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);
}

+5
source share
2 answers

, inet_addr("192.168.10.0") | ~(inet_addr("255.255.240.0")) inet_addr("192.168.15.255"), .

, , , , . ? ?

0

All Articles