I'm trying to write a simple client to receive multicast data. I've tried many different iterations and none of them work. The environment that I am using is .netcore 2.2.2 and in a linux environment. I can see that the data is being sent to the proper interface via tcpdump but my client always gets stuck at the receive. I also have a program that was written in Java by a previous developer which properly receives data from interfaces below so I can confirm that the route does indeed work.
Attempt #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");
Attempt#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");
}
Any help would be greatly appreciated.
FIXED using the following code
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());
}