我正在尝试在我的所有网络接口(2 个 LAN,一个 wifi)上发送一个多播数据包。我最初遵循本教程。
我遇到的问题是,数据包似乎只有我的一个 IP 地址。
这是我当前的代码。
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);
}
}
我尝试手动进行:
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);
}
}
}
这可行,但这意味着我必须创建与 IP 一样多的套接字(在此示例中,我在每次发送时创建它们,但这只是一个测试),而且我不喜欢我必须获得的方式我所有的IP。
那么这样做的正确方法是什么?
编辑第二个奖励问题:为什么当我在指定远程地址的本地 ip 中Connect
指定远程地址但不在Bind
?