简体   繁体   中英

UDP Broadcasting using winsock on a win 10 machine not working

I'm making a LAN multiplayer game using c++ and winsock, were I've created my own protocol for connecting two machines to eachother. The protocol involves broadcasting a message over the local LAN, which strangely isn't working on one of the two machines I'm using to test my code. The strange part is that it's as mentioned working on one machine, whereas not on the other. I've used wireshark to monitor outgoing packets, and the packets isn't being sent on the failing machine, even though that sendto() is returning the correct amount of bytes. The only difference between the machines is that one (the failing one) is using win10 and the other win8.

Is there any difference in the winsock library/networking layer between windows 10 and windows 8 that could cause this? Else, do you have any other ideas of what could cause the failure?

The code for sending a broadcast looks like this:

sockaddr_in send_addr;
send_addr.sin_family = AF_INET;
send_addr.sin_port = htons(PORT);
send_addr.sin_addr.s_addr = inet_addr("255.255.255.255");

int iResult = sendto(sock,
    reinterpret_cast<char*>(&packet),
    sizeof(Packet),
    0,
    (SOCKADDR *)&send_addr,
    sizeof(send_addr));

if (iResult == SOCKET_ERROR)
{
    printf("Failed to send broadcastmsg");
}

And the code to recieve it looks like this:

sockaddr_in sender_addr;
int sender_addrLen = sizeof(sender_addr);

Packet recvdPacket = {};

int iResult = recvfrom(sock,
    reinterpret_cast<char*>(&recvdPacket),
    sizeof(recvdPacket),
    0,
    (SOCKADDR*)&sender_addr,
    &sender_addrLen);

if (iResult > 0)
{
    return recvdPacket;
}
return Packet{};

You need to enable broadcast setting SO_BROADCAST before sending a broadcast message: https://msdn.microsoft.com/en-us/library/windows/desktop/ms740476(v=vs.85).aspx , Why do we need SocketOptions.SO_BROADCAST to enable broadcast?

char broadcast = 1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast))

Also you should use directed broadcast (for example, 192.168.0.255) instead of Internet broadcast (255.255.255.255). I believe you don't need Internet broadcast.

Also, can you print the value returned by sendto? is iResult == sizeof(Packet)?

Last, which is the size of Packet? Is it a class? you are reinterpreting &packet as a char *. You must be sure there is no error there.

Could broadcast be blocked in the Win10 PC? I don't know if it's possible.

Consider using multicast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM