Fail to listen to UDP Port with boost::asio

非 Y 不嫁゛ 提交于 2020-01-02 06:45:08

问题


I have a server that gathers information and broadcasts some messages across the local network. I'm using boost::asio to broadcast these via UDP on port 8079 and I can verify with WireShark that these packets are actually broadcasted as intended.

Now, naturally, I want to follow up with a listener that can react to these messages, but I am struggling to receive anything. My current approach is:

boost::asio::io_service io_service;
boost::asio::ip::udp::socket socket(io_service);
boost::asio::ip::udp::endpoint local(
    boost::asio::ip::address::from_string("192.168.2.102"),
    8079);
boost::system::error_code error;

std::cout << "Local bind: " << local << std::endl;

socket.open(boost::asio::ip::udp::v4(), error);
if(!error) {
    socket.bind(local);
    boost::array<char, 2048> buf;
    boost::asio::ip::udp::endpoint server;
    std::cout << "Listening..." << std::endl;
    while(true) {
        size_t len = socket.receive_from(boost::asio::buffer(buf), server);
        std::cout << "Received data:" << std::endl;
        std::cout.write(buf.data(), len);
        std::cout << std::endl;
    }
}

But I never receive anything. Using the debugger, I found that I'm just stuck in receive_from forever, and I don't know why.

Some further information (mostly from Wireshark) that I'm not sure about whether it could be causing these problems: Server and client are running on the same machine. The server is sending a sending an 88 bytes message every two seconds from port 34050 (source) to 8079 (destination). 192.168.2.102 is the ip of the machine within the local network.


回答1:


IIRC, you have to bind to INADDR_ANY to receive broadcast packets. There are quite a few discussions in Linux message lists discussing this issue. Beyond this, make sure that the netmask matches on both computers. If the broadcast is going to 192.168.255.255 and your client netmask is 255.255.255.0, you will not receive the packets.




回答2:


You don't call io_service::run on any thread so the completion handlers are never called even if data is received.



来源:https://stackoverflow.com/questions/9337736/fail-to-listen-to-udp-port-with-boostasio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!