Sending broadcast in Linux via Sockets

11,141

Solution 1

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

Solution 2

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.

Share:
11,141
shaggy
Author by

shaggy

Updated on June 04, 2022

Comments

  • shaggy
    shaggy almost 2 years

    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!