c++ - UDP 广播未收到

标签 c++ c udp udpclient

我对网络编程非常陌生,并且发现其中很少有很难理解。

我有一个工作程序,它向本地设备发送消息,让其知道它的工作原理,就像保持事件状态一样。现在我想更改为广播,以便可以在本地任何地方查看其状态。因此,在看到几个在线示例后,我将工作代码更改为如下所示

//inet_aton(pIPAddress, &(TxAddr.sin_addr)); //working
TxAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); //NOT WORKING

还有什么我需要添加的广播工作..请建议。我的完整程序可以在下面找到。我也使用了wireshark,但在广播时发现没有UDP数据包。但是当我使用特定IP时可以..

/// Rx buffer size
static int RxBufSize = UDP_RX_BUF_SIZE;

int Udp::UDPInit (tConfigIniData *pConfig)
{

  pIPAddress = pConfig->pIPAddress;
  TxPort = pConfig->UdpTxPort;

  // Tx socket
  TxSkt = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if (TxSkt == -1)
  {
    goto Exit;
  }
  else
  {
   Log (EVENT|TEXTFILE, UDP, "Successful tx socket creation\n");
  }

Exit:
 Log (EVENT|TEXTFILE, UDP, "() = %d\n", TxSkt);

  return TxSkt;
}

int Udp::UDPSend (tUdpInfo _udpInfo)
{
  int Ret = 0;

  struct sockaddr_in TxAddr = {0};
  TxAddr.sin_family = AF_INET;

  TxAddr.sin_port   = htons(TxPort);
  //TxAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
  inet_aton(pIPAddress, &(TxAddr.sin_addr)); //working

  // And send
  if (TxSkt != -1)
  {
   Log (EVENT|TEXTFILE, UDP, "Sending %d bytes: %p\n", sizeof(_udpInfo), &_udpInfo);

    ssize_t Res = sendto(TxSkt, (const void*)(&_udpInfo), sizeof(_udpInfo), 0, (const struct sockaddr *)&TxAddr, sizeof(TxAddr));
    if (Res < 0)
    {
     Log (EVENT|TEXTFILE|ERROR|CONSOLE, UDP,"ERR: Failed to write to TX socket (%d,%s)\n", errno, strerror(errno));
    }
    Ret = 0;
  }
  else
  {
    // No socket, indicate error
   Log (EVENT|TEXTFILE|ERROR|CONSOLE, UDP, "ERR: No Tx Socket exists\n");
    Ret = -EBADFD;
  }

 Log (EVENT|TEXTFILE, UDP, "()\n");
  // TxPortumber++;
 // cout<< "port NUmber used : "<<TxPortumber<<"\n";

  return Ret;
}

void Udp::UDPDeinit (int UDPFd)
{
 Log (EVENT|TEXTFILE, UDP, "(UDPFd %d)\n", UDPFd);

  // tidy up interfaces
  int Res = close(UDPFd);
  if (Res < 0)
  {
   Log (EVENT|TEXTFILE|ERROR|CONSOLE, UDP, "UDP: Close Failed: %d, %s - %s\n", errno, strerror(errno), __func__);
  }
}

最佳答案

提示,setsockopt SO_BROADCAST ,还有search SO .

关于c++ - UDP 广播未收到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17164105/

相关文章:

c++实现定时回调函数

c - 如何在文件中搜索新输入​​的匹配项?

mobile - NAT 后面到 NAT 后面的连接

java - 如何固定数据包的传输路径,从而使延迟保持静态?

c++ - C++ 中的字符串类可以有多大?

c++ - 'int' 使用 static_cast 转换为 'const int',但既不初始化也不具有 const 行为

c++ - 在构造函数中分配数组时出错

c - 从不兼容的指针类型初始化 - C 结构

c - 尝试对文件求和并通过管道/叉/进程传输时出错?

networking - 识别假 UDP 数据包