UDP组播未接收到数据

时间:2019-03-11 14:43:12

标签: c# .net-core udp multicast

我正在尝试编写一个简单的客户端来接收多播数据。我尝试了许多不同的迭代,但是都没有用。我正在使用的环境是.netcore 2.2.2和Linux环境。我可以看到数据正在通过tcpdump发送到正确的接口,但是我的客户端总是卡在接收端。我也有一个由以前的开发人员用Java编写的程序,该程序可以从下面的接口正确接收数据,因此我可以确认路由确实有效。

尝试#1

mcastSocket = new Socket(AddressFamily.InterNetwork,
                         SocketType.Dgram,
                         ProtocolType.Udp);
IPAddress localIPAddr = IPAddress.Parse("10.51.254.2");
EndPoint localEP = (EndPoint)new IPEndPoint(localIPAddr, mcastPort);

mcastSocket.Bind(localEP);

mcastOption = new MulticastOption(mcastAddress, localIPAddr);

mcastSocket.SetSocketOption(SocketOptionLevel.IP,
                  SocketOptionName.AddMembership,
                  mcastOption);

EndPoint remoteEp = new IPEndPoint(mcastAddress, mcastPort);
// I have tried using (localIPAddr, mcastPort), (IPAddress.Any, 0),
// (localIPAddr, 0), (IPAddress.Any, mcastPort)

byte[] arr = new byte[4096];
Console.WriteLine("Socket setup");
var receivedBytes = mcastSocket.ReceiveFrom(arr, ref remoteEp );
Console.WriteLine("Got data");

尝试#2

UdpClient client = new UdpClient();

client.ExclusiveAddressUse = false;
IPEndPoint localEp = new IPEndPoint(IPAddress.Parse("10.51.254.2"), 14382);

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

client.Client.Bind(localEp);            
client.JoinMulticastGroup(IPAddress.Parse("224.0.31.130"), IPAddress.Parse("10.51.254.2"));

Console.WriteLine("Listening this will never quit so you will need to ctrl-c it");
IPEndPoint remoteEp = new IPEndPoint(IPAddress.Parse("224.0.31.130"), 14382);
EndPoint remoteEndPoint = (EndPoint) new IPEndPoint(IPAddress.Any, 0);
while (true)
{
    Byte[] data = client.Receive(ref remoteEndPoint);                
    Console.WriteLine("got data");
}

任何帮助将不胜感激。

使用以下代码修复

try
{
    mcastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

    IPAddress localIPAddr = IPAddress.Parse("10.51.254.2");                
    IPEndPoint localEP = new IPEndPoint(IPAddress.Any, mcastPort);          
    mcastSocket.Bind(localEP);

    MulticastOption option = new MulticastOption(mcastAddress, localIPAddr);              
    mcastSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, option);

    EndPoint remoteEp = new IPEndPoint(localIPAddr, mcastPort);

    byte[] arr = new byte[4096];

    while (true)
    {
        var receivedBytes = mcastSocket.ReceiveFrom(arr, ref remoteEp);
                    Console.WriteLine($"Got data {receivedBytes}");
    }
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

0 个答案:

没有答案