C# 从所有网络适配器发送广播消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/436778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send broadcast message from all network adapters
提问by sdasari
I have an application that sends broadcast messages and listens for response packets. Below is the code snippet.
我有一个发送广播消息并侦听响应数据包的应用程序。下面是代码片段。
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
m_socket.Bind(new IPEndPoint(IPAddress.Any, 2000));
m_socket.BeginSendTo(
buffer,
0,
buffer.Length,
SocketFlags.None,
new IPEndPoint(IPAddress.Broadcast, 2000),
Callback),
null
);
When I run the application the broadcast message was not being sent. On my machine I have three network adapters. One is my local network adapter and other two are VMWare network virtual adapters. When I run my application I can see (using wireshark network capture) that the broadcast message is being sent from one of the VMWare network adapters.
当我运行应用程序时,广播消息没有被发送。在我的机器上,我有三个网络适配器。一个是我的本地网络适配器,另外两个是 VMWare 网络虚拟适配器。当我运行我的应用程序时,我可以看到(使用wireshark 网络捕获)广播消息是从 VMWare 网络适配器之一发送的。
I would like to modify the code so that the broadcast message will be sent from all network adapters on the pc. What is the best way to do that?
我想修改代码,以便从 PC 上的所有网络适配器发送广播消息。最好的方法是什么?
采纳答案by JD Conley
You can use the following to get all your IP Addresses (and a lot more). So you can iterate through the list and bind (like Jon B said) to the specific IP you want when you send out your multicast.
您可以使用以下内容获取所有 IP 地址(以及更多)。因此,当您发送多播时,您可以遍历列表并绑定(如 Jon B 所说)到您想要的特定 IP。
foreach (var i in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
foreach (var ua in i.GetIPProperties().UnicastAddresses)
Console.WriteLine(ua.Address);
回答by Jon B
When you call Bind(), you are setting the local IP end point. Instead of using IPAddress.Any, use the IP address of the NIC that you want to send from. You'll need to do this separately for each NIC.
当您调用 Bind() 时,您正在设置本地 IP 端点。不要使用 IPAddress.Any,而是使用要从中发送的 NIC 的 IP 地址。您需要为每个 NIC 单独执行此操作。
回答by Puscasu Razvan
You can use IPAddress.Any when constructing the tcpListener. This will bind the tcp listener to all interfaces
您可以在构造 tcpListener 时使用 IPAddress.Any。这会将 tcp 侦听器绑定到所有接口
回答by Peyman
Check this http://salaam.codeplex.com/I and my friend developed a class library called Salaam. download the source code or use the binaries (.dll) to use it.
检查这个http://salaam.codeplex.com/我和我的朋友开发了一个名为 Salaam 的类库。下载源代码或使用二进制文件 (.dll) 来使用它。