由于工作需要,我需要实现一个UDP发送广播包到设备的需求。如果是linux下,那很简单。但是上位机要求是windows.
网上简单搜了一下,代码很多。 可我发现就是没办法在设备端收到我发送的广播包。
都不用检查防火墙,我电脑的防火墙早关了。
后来看到stackoverflow.com上面有人也遇到了同样的问题,但是没有给出具体的例子
简单来说原因是这样的:win7之前的系统,发送广播包是到pc所有的网卡上的。 win7及以后,是要求制定广播包的源IP.简单说bind的IP不能是INADDR_ANY.
下面的例子是可以工作的。
注:%99代码是网上的,我只改了几行。
//--------------------------------------------
#include "stdafx.h"
#include <WinSock2.h>
#include <Windows.h>
#include <string.h>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
int main(int argc, char *argv[])
{
SOCKET s;
struct sockaddr_in server, si_other;
int slen ;
WSADATA wsa;
slen = sizeof(si_other) ;
//Initialise winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//Create a socket
if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
{
printf("Could not create socket : %d" , WSAGetLastError());
}
printf("Socket created.\n");
int so_broadcast = TRUE;
setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&so_broadcast, sizeof(so_broadcast));
//Prepare the sockaddr_in structure
server.sin_family = AF_INET;
/* the card IP of the PC*/
printf("send BC package on the port with IP %s\n", argv[1]);
server.sin_addr.s_addr = inet_addr(argv[1]); -----------------> SPECIFIC THE IP HERE
server.sin_port = htons( 9989 );
//Bind
if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
puts("Bind done");
si_other.sin_family = AF_INET;
si_other.sin_addr.S_un.S_addr =htonl(INADDR_BROADCAST);
//unsigned long ip = inet_addr("172.17.255.255");
//b_addr.sin_addr.S_un.S_addr =htonl(ip);
si_other.sin_port = htons(9988);
//keep listening for data
while(1)
{
//buf the buffer by filling null, it might have previously received data
char buf[128] = "ADD YOUR PAYLOAD HERE";
//now reply the client with the same data
if (sendto(s, buf, strlen(buf), 0, (struct sockaddr*) &si_other, slen) == SOCKET_ERROR)
{
printf("sendto() failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("send... %d\n", WSAGetLastError());
Sleep(1000);
}
closesocket(s);
WSACleanup();
return 0;
}