0

I am trying to broadcast data but the output is udp send failed. I chose a random port 33333. What's wrong with my code?

int main()
{
   struct sockaddr_in udpaddr = { sin_family : AF_INET };
   int xudpsock_fd,sock,len = 0,ret = 0,optVal = 0;

   char buffer[255];
   char szSocket[64];
   memset(buffer,0x00,sizeof(buffer));
   memset(&udpaddr,0,sizeof(udpaddr));

       udpaddr.sin_addr.s_addr = INADDR_BROADCAST;
       udpaddr.sin_port = htons(33333);

   xudpsock_fd = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);

   optVal = 1;
   ret = setsockopt(xudpsock_fd,SOL_SOCKET,SO_BROADCAST,(char*)&optVal,sizeof(optVal));
   strcpy(buffer,"this is a test msg");

   len = sizeof(buffer);
   ret = sendto(xudpsock_fd,buffer,len,0,(struct sockaddr*)&udpaddr,sizeof(udpaddr));

       if (ret == -1)
          printf("udp send failed\n");
       else
          printf("udp send succeed\n");

   return (0);
}
Brknl
  • 97
  • 3
  • 9
  • What does errno say about the failure? – Joe Jul 02 '13 at 12:55
  • It says 101, Nertwork is unreachable but i don't understand what does it mean with unreachable,i can send tcp packets on the same network. – Brknl Jul 02 '13 at 13:14
  • Just because a TCP connection will traverse the network it doesn't mean that the UDP broadcast will. – Joe Jul 02 '13 at 13:22
  • see the following link : http://stackoverflow.com/questions/2782259/sendto-network-unreachable – suneet saini Jul 02 '13 at 13:26
  • I solved the problem. I changed the udpaddr.sin_addr.s_addr = INADDR_BROADCAST; to udpaddr.sin_addr.s_addr = inet_addr("127.255.255.255"); and it works but i don't understand why. – Brknl Jul 02 '13 at 14:15

2 Answers2

1

One problem is that the address family you are trying to send to is zero (AF_UNSPEC). Although you initialize the family to AF_INET at the top of the function, you later zero it out with memset.

On the system I tested with, the send actually works anyway for some strange reason despite the invalid address family, but you should definitely try fixing that first.

Celada
  • 21,627
  • 4
  • 64
  • 78
0

You probably had a problem with your default route (eg, you didn't have one). sendto needs to pick an interface to send the packet on, but the destination address was probably outside the Destination/Genmask for each defined interface (see the 'route' command-line tool).

The default route catches this type of packet and sends it through an interface despite this mismatch.

Setting the destination to 127.255.255.255 will usually cause the packet to be sent through the loopback interface (127.0.0.1), meaning it will be able to be read by applications that (in this case) are run on the local machine.

user2869816
  • 3
  • 1
  • 3