问题
I'm testing a simple socket setup in which a server listens on a specified port, and a client sends a broadcast packet which should be received by that server.
This setup works fine when sending messages directly (i.e. not broadcasting), but when broadcasting the packet is never received on the server.
Some of the code (trimmed down with error checking removed, for simplicity):
// Client (broadcast sender)
// Create and bind the client socket
clientSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(5678);
sockAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
bind(clientSocket, (sockaddr*)(&sockAddr), sizeof(sockAddr));
u_long uMode = 1;
ioctlsocket(clientSocket, FIONBIO, &uMode);
char broadcast = 1;
setsockopt(clientSocket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast));
// ...
// Send the packet
sockaddr_in sockAddress;
sockAddress.sin_family = AF_INET;
sockAddress.sin_addr.S_un.S_addr = htonl(INADDR_BROADCAST);
sockAddress.sin_port = htons(5679);
char const* pPacket = "Test";
size_t uPacketSize = strlen(pPacket) + 1;
sendto(clientSocket, pPacket, (int)uPacketSize, 0, (sockaddr*)&sockAddress, sizeof(sockAddress));
-
// Server (listener)
// Create and bind the server socket
serverSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
sockaddr_in sockAddr;
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(5679);
sockAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
bind(serverSocket, (sockaddr*)(&sockAddr), sizeof(sockAddr));
u_long uMode = 1;
ioctlsocket(serverSocket, FIONBIO, &uMode);
// ...
char pBuffer[1024];
while (true)
{
int iRecvSize = recv(serverSocket, pBuffer, 1024, 0);
if (iRecvSize)
{
printf("Received packet\n");
}
}
回答1:
(Should be a comment, but my reputation is not high enough)
I don't know if this applies to you, but there is a unintuitive behavior with broadcasts on recent versions of Windows. If you have multiple physical Ethernet adapters, broadcasts will only be received on the "preferred" interface (where "preference" is determined by Windows' routing table)
See the following for an explanation and potential fix: https://github.com/dechamps/WinIPBroadcast
Another temporary fix would be to disable all other network adapters to make sure the broadcast is received on the correct one (in Control Panel/Network and Sharing Center/Change adapter settings).
来源:https://stackoverflow.com/questions/41022253/udp-winsock-not-receiving-broadcast-packets