c ++从广播电台接收数据包

时间:2013-12-03 13:51:13

标签: c++ networking

我正在编写一个c ++客户端来接收来自服务器的数据包(UDP广播)。这是一个硬件开关(仅限一个方向)系统,因此我没有关于发件人地址或任何其他信息的信息。它全部编译并绑定,但没有收到数据包。

WSAStartup(0x0101, &_wsaData);
memset((char *)&_sockaddr, 0, sizeof(_sockaddr));
_sockaddr.sin_addr.s_addr   = _nAdapterIp;
_sockaddr.sin_family        = _nadressFam;
_sockaddr.sin_port      = _usPort; //Gave it a try with (0) - also not working
_socket = socket(_nadressFam, SOCK_DGRAM, 0); //Gave it a try with (17) - UDP for the 3 rd parameter - not working
char broadcast='1';
setsockopt(_socket, SOL_SOCKET, SO_BROADCAST, &broadcast ,sizeof(broadcast));
bind(_socket, (sockaddr*) & _sockaddr, sizeof (_sockaddr));
char* recvbuf = new char[_nPacketSize + 1];
int nSize = recv(_socket, recvbuf, _nPacketSize + 1, 0);

1 个答案:

答案 0 :(得分:1)

即使我不确定它是你的代码段中唯一的警告,也要回答一下评论

您对setsockopt的通话有效,但您的第四个参数并不好,因为您传递字符 1,实际上是十进制值49。

unsigned char broadcast = 1;
if (setsockopt(_socket, SOL_SOCKET, SO_BROADCAST, &broadcast ,sizeof(broadcast)) == -1) {
  //handle errors appropriately
}