Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a UDP multicast across the local network in c#?

I am trying to get some simple UDP communication working on my local network.

All i want to do is do a multicast to all machines on the network

Here is my sending code

    public void SendMessage(string message)
    {
        var data = Encoding.Default.GetBytes(message);
        using (var udpClient = new UdpClient(AddressFamily.InterNetwork))
        {
            var address = IPAddress.Parse("224.100.0.1");
            var ipEndPoint = new IPEndPoint(address, 8088);
            udpClient.JoinMulticastGroup(address);
            udpClient.Send(data, data.Length, ipEndPoint);
            udpClient.Close();
        }
    }

and here is my receiving code

    public void Start()
    {
        udpClient = new UdpClient(8088);
        udpClient.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50);

        receiveThread = new Thread(Receive);
        receiveThread.Start();
    }

    public void Receive()
    {
        while (true)
        {
            var ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
            var data = udpClient.Receive(ref ipEndPoint);

            Message = Encoding.Default.GetString(data);

            // Raise the AfterReceive event
            if (AfterReceive != null)
            {
                AfterReceive(this, new EventArgs());
            }
        }
    }

It works perfectly on my local machine but not across the network.

-Does not seem to be the firewall. I disabled it on both machines and it still did not work.

-It works if i do a direct send to the hard coded IP address of the client machine (ie not multicast).

Any help would be appreciated.

like image 491
Simon Avatar asked Apr 20 '09 07:04

Simon


2 Answers

Does your local network hardware support IGMP?

It's possible that your switch is multicast aware, but if IGMP is disabled it won't notice if any attached hardware subscribes to a particular multicast group so it wouldn't forward those packets.

To test this, temporarily connect two machines directly together with a cross-over cable. That should (AFAICR) always work.

Also, it should be the server half of the code that has the TTL argument supplied to JoinMulticastGroup(), not the client half.

like image 85
Alnitak Avatar answered Oct 05 '22 06:10

Alnitak


I've just spent 4 hours on something similar (I think), the solution for me was:

client.Client.Bind(new IPEndPoint(IPAddress.Any, SSDP_PORT));
client.JoinMulticastGroup(SSDP_IP,IP.ExternalIPAddresses.First());
client.MulticastLoopback = true;

Using a specific (first external) IP address on the multicast group.

like image 38
Uri Maimon - Nominal Avatar answered Oct 05 '22 05:10

Uri Maimon - Nominal