Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to broadcast UDP messages to all computers in a local network using boost::asio. Working through the examples I came up with

try {
    socket.open(boost::asio::ip::udp::v4());
    boost::asio::socket_base::broadcast option(true);
    socket.set_option(option);
    endpoint = boost::asio::ip::udp::endpoint(
        boost::asio::ip::address::from_string("192.168.1.255"),
        port);
}
catch(std::exception &e) {
}

and want to broadcast messages from my queue with

while(!queue.empty()) {
    std::string message = queue.front();
    boost::system::error_code ignored_error;
    socket.send_to(
        boost::asio::buffer(message),
        endpoint,
        0, ignored_error);
    queue.pop_front();
}

but my code throws an exception invalid argument exception in the first code block. It works fine for 127.0.0.1 though. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
415 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try the following code snippet to send a UDP broadcast, utilizing the ba::ip::address_v4::broadcast() call to get an endpoint:

    bs::error_code error;
    ba::ip::udp::socket socket(_impl->_ioService);

    socket.open(ba::ip::udp::v4(), error);
    if (!error)
    {
        socket.set_option(ba::ip::udp::socket::reuse_address(true));
        socket.set_option(ba::socket_base::broadcast(true));

        ba::ip::udp::endpoint senderEndpoint(ba::ip::address_v4::broadcast(), port);            

        socket.send_to(data, senderEndpoint);
        socket.close(error);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...