简体   繁体   中英

C# UDP multicast receive not working (async or sync)

I'm adding a multicast listening feature for an application I'm developing. A device I'm connecting to will send out a multicast packet every second in certain scenarios, and I'd like the user to be able to listen for that packet (if it's being sent).

I can see the multicast packets being continuously sent from the device using Wireshark, so I know they exist and I know I'm using the correct multicast group and port number. I've tried dozen of different ways without any luck to get my application to capture the packets. If I send a test multicast packet from the application itself it receives it no problem. I've tried to receive the packets both async and sync, no change. I'm really stumped on this one and not sure what I'm doing wrong. Every example I've found leads me to believe this should be working.

My multicast udp listener class:

   class MulticastClient
{
    private UdpClient client;
    private IPEndPoint localEp;
    private IPAddress multicastAddress;

    public byte[] receivedData { get; private set; }

    public MulticastClient(string multicastIP, int port)
    {
        localEp = new IPEndPoint(IPAddress.Any, port);
        client = new UdpClient(AddressFamily.InterNetwork);

        client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        client.ExclusiveAddressUse = false;

        client.Client.Bind(localEp);

        this.multicastAddress = IPAddress.Parse(multicastIP);
        client.JoinMulticastGroup(this.multicastAddress);            
    }

    public async Task Listen()
    {
        UdpReceiveResult result = await client.ReceiveAsync();
        receivedData = result.Buffer;    
    }
}

The button click that kicks it off:

MulticastClient client = new MulticastClient("239.255.0.1", 32768);

        await Task.Run(async () =>
        {
            await client.Listen();
        });

        byte[] receivedData = client.receivedData;

        if (receivedData != null)
        {
            //Here I display useful information about the packet to the user
        }

Here is a snippet of a packet capture, showing the multicast packets that I can't seem to receive: Wireshark packet capture

Got it to work using a variation of this post.

@jdweng made me realize it when he/she asked about multiple adapters, I had several virtual NICs for VMs that were likely joining ht multicast group instead of my actual hardware NIC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM