4

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.

Sam Miller
  • 23,808
  • 4
  • 67
  • 87
nikolas
  • 8,707
  • 9
  • 50
  • 70
  • 1
    Try "0.0.0.0" or `ip::address_v4::any` for your local endpoint address. – Emile Cormier Feb 18 '12 at 04:15
  • Does your receiver need to bind to a specific network interface? – Emile Cormier Feb 18 '12 at 04:39
  • @Emile Cormier `ip::address_v4::any()` does not change anything besides being bound to `0.0.0.0:8079`. Concerning your second question, I think `bind` is required for specifying the port you want to listen on; am I wrong? – nikolas Feb 18 '12 at 12:01
  • Yes, as I understand it, bind specifies the port. But bind is also used to specify the network interface. Specifying "0.0.0.0" (or equivalently `ip::address_v4::any`) means that you don't care what interface the broadcast traffic arrives on. – Emile Cormier Feb 18 '12 at 18:24

2 Answers2

4

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.

D.Shawley
  • 58,213
  • 10
  • 98
  • 113
-2

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

Andrei
  • 1