jeudi 23 juin 2016

sendto broadcast works but unicast doesn't

I have 2 programs running (program1, program2), both are sending and receiving UDP packets from each other using sockets I initialized.

My problem is if I send a broadcast out the TRANSMIT(TX) socket from program1, program2 receives the message but if I send a unicast (specify the IP to program2) program2 does not receive the message... the "sendto" function in program1 returns with the correct amount of packets sent so it is sending it out.

This makes no sense to me since the ip is in the netmask of the broadcast... My unicast should work too? I need the unicast tx to work also.

Can someone let me know what I'm doing wrong? I believe I set up my socket correctly and configured it correctly or it woudln't work at all. The piece of code that I'm having trouble on is below:

Program1 Tx:

if ( ip == INADDR_BROADCAST || ip == 0 )
{
    addr.sin_addr.s_addr = htonl( bcast );
}
else
{
    addr.sin_addr.s_addr = htonl( ip );
    // If I comment above and uncomment below, program works.
    //addr.sin_addr.s_addr = htonl( bcast );
}
addr.sin_port = htons( port );


ret = sendto( fd,
              buf,
              n,
              flags,
              addr,
              addr_len );

Some configurations of my socket1 is:

// Set up tx socket
s_addr.sin_family      = AF_INET;
s_addr.sin_addr.s_addr = htonl( own_ip );
s_addr.sin_port        = htons( 6060 );

Program2 Rx:

rx_len = recvfrom( fd, 
                   &rx_msg, 
                   sizeof ( rx_msg ), 
                   0,
                   (struct sockaddr *)&c_addr, 
                   &len );

Some configurations of my socket2 is:

s_addr.sin_family      = AF_INET;
// Must be INADDR_ANY to receive broadcasts
s_addr.sin_addr.s_addr = htonl( INADDR_ANY );
s_addr.sin_port        = htons( 6070);
if ( (ret = bind( fd, 
                  (struct sockaddr *)&s_addr, 
                   sizeof (s_addr) )) != 0 )

Aucun commentaire:

Enregistrer un commentaire