Whats does it mean for a client\server to broadcast?

59 Views Asked by At

I'm reading "Bjee's Guide to Network Programming Using Internet Sockets" and I'm trying to understand what's the meaning of "Broadcasting" (let's say, of a client). Does it means that the client sends packets to everyone connected to the local network? If so, can we send packet only to a set of connections on this network? I know that there's this "Broadcast address" thing, but I'm having difficulties to understand why do we need it, if we'll send the broadcast to anyone on the local network anyway?

Here's the code example from his book, re-written by me (see chapter "6.5. Broadcast Packets-Hello,World!"):

#define SERVERPORT 4950
#define SERVERIP "192.168.1.1" /* should it be 255.255.255.255 ? */


int main()
{
    int sockfd;
    int broadcast = 1;    
    struct sockaddr_in their_addr;
    char buf[] = "This is the client's buffer";

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast,
                                         sizeof(broadcast));

    their_addr.sin_family = AF_INET;
    their_addr.sin_port = htons(SERVERPORT);
    inet_aton(SERVER_IP ,&their_addr.sin_addr);
    memset(&(their_addr.sin_zero), 0, 8));

    sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr*)&their_addr,
                                               sizeof(struct sockaddr));

    return 0;
}
    
0

There are 0 best solutions below