Home > Mobile >  Broadcast-Mono vs Core
Broadcast-Mono vs Core

Time:12-29

A strange thing I am observing on Linux. The following simple code is broadcasting through the whole LAN. I compile that simple project as Core project and/or Mono project (both for Linux). They seem to work normally, but only from Mono compilation I am able to catch UDP packets otherwise not (with Core).

public sealed class Broadcaster : IDisposable
{
   readonly IPEndPoint _ipEndPoint;
   readonly object _locker = new object();
   readonly Dictionary<string, UdpClient> _clients = new Dictionary<string, UdpClient>();

   public Broadcaster(ushort broadcastPort)
   {
       _ipEndPoint = new IPEndPoint(IPAddress.Broadcast, broadcastPort);
   }

   public void Send(string message)
   {
       var data = Encoding.ASCII.GetBytes(message);
       var host = Dns.GetHostEntry(Dns.GetHostName());
       var addressList = host.AddressList;
       var ip = addressList.Last();
       var ip_ = ip.ToString();
       lock (_locker)
       {
           if (!_clients.ContainsKey(ip_))
               _clients.Add(ip_, new UdpClient(new IPEndPoint(ip, 0)));
       }
       try
       {
           _clients[ip_].SendAsync(data, data.Length, _ipEndPoint);
           Console.WriteLine($"broadcast: {DateTime.UtcNow}");
       }
       catch (Exception ex)
       {
           Console.WriteLine($"unable to use host {ip} while broadcasting: "   ex);
       }
   }

   public void Dispose()
   {
       try
       {
           lock (_locker)
           {
               foreach (var client in _clients)
               {
                   client.Value.Close();
                   client.Value.Dispose();
               }
               _clients.Clear();
           }
       }
       catch (Exception ex)
       {
           Console.WriteLine("Network boadcaster finishing: "   ex);
       }
   }
}  

...and its usage:

static async Task Main(string[] args)
{
    var broadcaster = new Broadcaster(15015);
    while (true)
    {
        broadcaster.Send($"Broadcaster: { DateTime.UtcNow.ToString("HH:mm:ss.fff")}");
        await Task.Delay(1000);
    }
}

Already checked (bash - no graphical UI on Linux):

  • ufw allow 15005/udp
  • The other computer in addition to Broadcast receiving app (which catches fine the packets for Mono broadcaster) is now equiped with Wireshark that just confirmng my observation.

Please, what is the problem with the Core version of Broadcaster? Do I need to change it, or tell Linux "hey this app is allowed to broadcast, or what"? What is Mono doing differently than Core?

CodePudding user response:

Different implementations set different default values when talking to native socket API. So, in your case, you should set UdpClient.EnableBroadcast to true so that .NET Core can send out broadcast requests.

Reference

  • Related