Howto send UDP Broadcast messages for Module running on Azure IoT Runtime

105 views Asked by At

I need to send a UDP Broadcast to the network connected to my device from an Container running as a module inside the Azure IoT Edge Runtime.

I've exported my udp port in the module configuration

{
  "ExposedPorts": {
    "7808/udp": {}
  },
  "HostConfig": {
    "PortBindings": {
      "7808/udp": [
        {
          "HostPort": "7808"
        }
      ]
    }
  }
}

Unicasts work fine. But i can't send a Broadcast to the outside world.

I've already tried to use the devices dedicated network broadcast IP without success.

Sample Code:

// initialize UdpClient
var ep = new IPEndPoint(IPAddress.Any, SharedPort);;
var _exclusiveConn = new UdpClient { ExclusiveAddressUse = true };
_exclusiveConn.Client.Bind(ep);
_exclusiveConn.EnableBroadcast = true;

// send
_exclusiveConn.Send(buffer, bufferlength, ep);


1

There are 1 answers

2
Sampath On
  • Using Reference for Azure IoT Edge UDP Client module.

Code:


using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

class Program
{
    private const int SharedPort = 7808;

    static void Main(string[] args)
    {
        try
        {
            // Broadcast address for IPv4
            var broadcastAddress = new IPEndPoint(IPAddress.Parse("255.255.255.255"), SharedPort);

            // Initialize UdpClient
            var udpClient = new UdpClient { ExclusiveAddressUse = false }; // Allow multiple clients to bind to the same port
            udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, SharedPort));
            udpClient.EnableBroadcast = true;

            // Message to send
            string message = "Hello, Broadcast World!";
            byte[] buffer = Encoding.UTF8.GetBytes(message);

            // Send the UDP broadcast message
            udpClient.Send(buffer, buffer.Length, broadcastAddress);

            Console.WriteLine("UDP broadcast message sent: " + message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

enter image description here

enter image description here

  • For more details refer Azure IoT Edge UDP Client module and git