Send UDP broadcast with use of glib

859 views Asked by At

I am trying to write a simple application that sends and receives broadcasts. For testing purposes. However something doesn't work. Receive command seems to work, however sending fails. Could anyone help? Important is that I have to use glib sockets.

My code for receiving:

    GError *err = nullptr;
    GInetAddress *iaddr = g_inet_address_new_any(G_SOCKET_FAMILY_IPV4);
    GSocketAddress *addr = g_inet_socket_address_new(iaddr, 7070);
    GSocket *sock = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &err);
    if (err)
        WERROR("ERR1");

    g_socket_set_broadcast(sock, TRUE);
    g_socket_bind(sock, addr, TRUE, &err);
    if (err)
        WERROR("ERR2");
    char buf[200] = {0};
    WDEBUG("LISTENING!");
    g_socket_receive(sock, buf, 200, nullptr, &err);
    if (err)
        WERROR("ERR3");
    else
        WDEBUG("BUF = %s", buf);

Application starts to wait for incoming packets. Here's code for sending a broadcast:

    GError *err = nullptr;
    GInetAddress *iaddr = g_inet_address_new_any(G_SOCKET_FAMILY_IPV4);
    GSocketAddress *addr = g_inet_socket_address_new(iaddr, 7070);
    GSocket *sock = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &err);
    if (err)
        WERROR("ERR1");
    g_socket_set_broadcast(sock, TRUE);
    g_socket_send_to(sock, addr, "TEST", 5, nullptr, &err);
    if (err)
        WERROR("ERR2");
    WDEBUG("SENT!");

I've been looking for some examples on sending broadcasts with glib, however I failed to find them. Can anybody help?

1

There are 1 answers

0
dalicrosKH On

You shall create specific broadcast address.

Instead of

GInetAddress *iaddr = g_inet_address_new_any(G_SOCKET_FAMILY_IPV4);

use for example

GInetAddress *iaddr = g_inet_address_new_from_string("127.255.255.255");

This will send broadcast to loopback interface.
For more details about broadcast address calculation see http://jodies.de/ipcalc.