Page 1 of 1

How To Send/Receive UDP Broadcasts

Posted: Thu Aug 01, 2019 2:33 pm
by felipe2028
Hello. New member here. I've seen a lot of posts by people who have implemented wxDatagramSocket for UDP broadcasts, but are having trouble receiving the broadcast responses. Was working on this myself and found a solution. Turns out trying to read incoming data on a socket flagged with wxSOCKET_BROADCAST was what was causing my problem (and probably what was causing issues for everyone else). The solution is to have two wxDatagramSockets.

Outgoing Setup

Code: Select all

wxIPV4address ipLocalAddressOut;
ipLocalAddressOut.AnyAddress();    // sets this to "0.0.0.0"

wxDatagramSocket socketOut = new wxDatagramSocket(ipLocalAddressOut, wxSOCKET_BROADCAST | wxSOCKET_NOBIND);

wxIPV4address ipBroadcastAddress;    // we will use this later to send traffic out
ipBroadcastAddress.BroadcastAddress();    // sets this to "255.255.255.255"
ipBroadcastAddress.Service(INT_UDP_PORT);
Incoming Setup

Code: Select all

wxIPV4address ipLocalAddressIn;
ipLocalAddressIn.AnyAddress();    // sets this to "0.0.0.0"
ipLocalAddressIn.Service(INT_UDP_PORT);

wxWindowID idSocket = wxIdManager::ReserveId();

wxDatagramSocket socketIn = new wxDatagramSocket(ipLocalAddressIn, wxSOCKET_NONE);
socketIn->SetEventHandler(*this, idSocket);
socketIn->SetNotify(wxSOCKET_INPUT_FLAG);
socketIn->Notify(true);

wxEvtHandler::Bind(wxEVT_SOCKET, &OnSocketInput, this, idSocket);
Send Broadcast

Code: Select all

void BroadcastDatagram(const char* data, size_t length) {
    socketOut->SendTo(ipBroadcastAddress, data, length)    // use outgoing address set up earlier
}
Handle Input

Code: Select all

void OnSocketInput(const wxSocketEvent& event) {
    // we are only notifying the event handler of wxSOCKET_INPUT events, so assume we have data to read
    char data[INT_MAX_PACKET_SIZE];
    memset(data, 0, INT_MAX_PACKET_SIZE);
    socketIn->Read(data, INT_MAX_PACKET_SIZE);
    // use socketIn->LastReadCount() to determine how much data actually came in when processing
}
This was done in Windows 10, using wxWidgets 3.1.2, compiled in Visual Studio 2019.