Question

I am very new to network programming and finding hard to understand few of them.

I have a working program which Sends messages to a local device to let it know its working like Keep alive. Now I want to change to broadcast so that can check its status any where locally. So I changed the working code to like below after seeing couple of online samples

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

is there anything more I need to add to work for broadcast ..Please advice . My complete program can be found below .I also used wireshark but found no UDP packet when I broadcast.But I can when I use specific 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__);
  }
}
Was it helpful?

Solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top