How to UDP Broadcast with C in Linux?

前端 未结 4 1605
一向
一向 2020-12-13 00:52

How to UDP Broadcast with C in Linux?

4条回答
  •  情歌与酒
    2020-12-13 01:14

    I wrote udp multicast server recently for testing. To subscribe to multicast you would subscribe your client to Multicast group 225.0.0.37 port 12346 and port 12345 (2 feeds - one feeds sends "Hello, World!" the other one "Bye, Office!").

    I've been using it for testing my client, both client and server run on the same box so there might be bits that may not work but give it a try first.

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    #include 
    
    
    #define BYE_OFFICE 12346
    #define HELLO_PORT 12345
    #define HELLO_GROUP "225.0.0.37"
    
    int main(int argc, char *argv[])
    {
        struct sockaddr_in addr;
        struct sockaddr_in addr2;
        int fd;
        int fd2;
        char *message = "Hello, World!";
        char *message2 = "Bye, Office!";
    
        if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
        {
            perror("socket");
            exit(1);
        }
    
        if ((fd2 = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
        {
            perror("socket");
            exit(1);
        }
    
        /* set up destination address */
        memset(&addr,0,sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr(HELLO_GROUP);
        addr.sin_port=htons(HELLO_PORT);
    
        memset(&addr2,0,sizeof(addr2));
        addr2.sin_family = AF_INET;
        addr2.sin_addr.s_addr = inet_addr(HELLO_GROUP);
        addr2.sin_port=htons(BYE_OFFICE);
    
        while (1)
        {
            if (sendto(fd, message, strlen(message), 0,(struct sockaddr *) &addr, sizeof(addr)) < 0)
            {
                perror("sendto");
                exit(1);
            }
            sleep(3);
            if (sendto(fd2, message2, strlen(message2), 0,(struct sockaddr *) &addr2, sizeof(addr2)) < 0)
            {
                perror("sendto2");
                exit(1);
            }
            sleep(3);
        }
    }
    

提交回复
热议问题