I'm trying to send a multicast packet on all my network interfaces(2 LAN, one wifi). I initialy followed this tutorial.
The problem I encounter, is that it seems that the packet seems to be with only one of my IP address.
Here is my current code.
private static void SendOnAllCards(int port, String address)
{
using (Socket mSendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse(address)));
mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255);
mSendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
mSendSocket.Bind(new IPEndPoint(IPAddress.Any, port));
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(address), port);
mSendSocket.Connect(ipep);
byte[] bytes = Encoding.ASCII.GetBytes("This is my welcome message");
mSendSocket.Send(bytes, bytes.Length, SocketFlags.None);
}
}
I tried to do it manually:
private static void SendOnAllCards(int port, string remoteAddressSrc)
{
foreach (IPAddress remoteAddress in Dns.GetHostAddresses(Dns.GetHostName()).Where(i=>i.AddressFamily == AddressFamily.InterNetwork))
{
using (Socket mSendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse(remoteAddressSrc)));
mSendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255);
mSendSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
mSendSocket.Bind(new IPEndPoint(IPAddress.Any, port));
IPEndPoint ipep = new IPEndPoint(remoteAddress, port);
mSendSocket.Connect(ipep);
byte[] bytes = Encoding.ASCII.GetBytes("This is my welcome message");
mSendSocket.Send(bytes, bytes.Length, SocketFlags.None);
}
}
}
This works, but it implies I've to create as many socket that I've IP(in this sample I create them on each send, but it's just a test), and I don't like the way I've to obtain all my IPs.
So what is the right way to do this?
Edit second bonus question: Why is this working when I specify the local ip in the Connect
, which specify the remote address, but doesn't on the Bind
?