简体   繁体   中英

Sending broadcast in Linux via Sockets

SOLVED please close the question (but I do not really know how:/ bad day)

Im trying to send broadcast in linux via sockets, it was always going out through both interfaces(ive got active eth0 and eth1, both in a different segments), but suddelny, it is going out just through the first one, eth0

Here is the code:

void sendBroad(char *dstIP, char *localIP)
{
    int sock;                         /* Socket */
    struct sockaddr_in broadcastAddr; /* Broadcast address */
    int broadcastPermission;          /* Socket opt to set permission to broadcast */
    unsigned int localIPLen;       /* Length of string to broadcast */


    /* Create socket for sending/receiving datagrams */
    if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
        perror("socket() failed");

    /* Set socket to allow broadcast */
    broadcastPermission = 1;
    if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission, 
          sizeof(broadcastPermission)) < 0)
        perror("setsockopt() failed");

    /* Construct local address structure */
    memset(&broadcastAddr, 0, sizeof(broadcastAddr));   /* Zero out structure */
    broadcastAddr.sin_family = AF_INET;                 /* Internet address family */
    broadcastAddr.sin_addr.s_addr = inet_addr(dstIP);   /* Broadcast IP address */
    broadcastAddr.sin_port = htons(BroadcastPort);      /* Broadcast port */

    localIPLen = strlen(localIP);  /* Find length of localIP */
    int j;
    for (j=0; j<1; j++) //doesnt mean anything so far, not important
    {
         /* Broadcast localIP in datagram to clients */
         if (sendto(sock, localIP, localIPLen, 0, (struct sockaddr *) 
               &broadcastAddr, sizeof(broadcastAddr)) != localIPLen)
             perror("sendto() sent a different number of bytes than expected");


    }
}

Any help with this issue?

Thanks in advance!

Your code looks OK at a quick glance. The problem may have been in the destination IP address.

NB you realize that a datagram arrives along with its source address anyway? You don't need to put the address into the payload as well. You could put something more specific in there such as an application identifier.

Just had to make fix the broadcast ports, it was mixed. The code itself is ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM