UDP广播未收到

时间:2013-06-18 08:31:24

标签: c++ c udp udpclient

我是网络编程的新手,很难理解其中的一些。

我有一个工作程序,它将消息发送到本地设备,让它知道它的工作状态如Keep alive。现在我想更改为广播,以便可以在本地检查其状态。因此,在看到几个在线样本后,我将工作代码改为如下所示

//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__);
  }
}

1 个答案:

答案 0 :(得分:0)

提示,setsockopt SO_BROADCAST,还有search SO

相关问题