仅从特定适配器(例如 192.168.101.1)发送 UDP 广播(255.255.255.255);在 Windows 上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/807651/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:22:46  来源:igfitidea点击:

Send UDP broadcast (255.255.255.255) from specific adapter (e.g. 192.168.101.1) only; on Windows

c#windowsudpbroadcast

提问by nietras

Solution for Windows XP or higher. Preferably in C# or else in C++.

Windows XP 或更高版本的解决方案。最好使用 C# 或 C++。

We do not want to broadcast using a subnet directed broadcast (e.g. 192.168.101.255) since the device we are trying to contact is not responding to this. Instead, we want to be able to send UDP datagram with a destination of 255.255.255.255 from a specific NIC/IPAddress only, such that the broadcast is NOT send out on other NICs.

我们不想使用子网定向广播(例如 192.168.101.255)进行广播,因为我们尝试联系的设备没有对此做出响应。相反,我们希望能够仅从特定的 NIC/IPAddress 发送目的地为 255.255.255.255 的 UDP 数据报,这样广播就不会在其他 NIC 上发送。

This means we have to circumvent the IP stack, which is, thus, the question. How can we circumvent the IP stack on windows to send a UDP/IP compliant datagram from a specific NIC/MAC address only?

这意味着我们必须绕过 IP 堆栈,这就是问题所在。我们如何绕过 Windows 上的 IP 堆栈以仅从特定的 NIC/MAC 地址发送符合 UDP/IP 的数据报?

回答by Chris Becke

Just bind() the socket to the desired interface instead of using INADDR_ANY ?

只需将套接字绑定()到所需的接口而不是使用 INADDR_ANY ?

// Make a UDP socket
SOCKET s = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
// Bind it to a particular interface
sockaddr_in name={0};
name.sin_family = AF_INET;
name.sin_addr.s_addr = inet_addr("192.168.101.3"); // whatever the ip address of the NIC is.
name.sin_port = htons(PORT);
bind(s,(sockaddr*)name);

回答by brickner

In order to use WinPcap to send a raw pcaket in C#, you can use Pcap.Net. It's a wrapper for WinPcap written in C++/CLI and C# and includes a packet interpretation and creation framework.

为了使用 WinPcap 在 C# 中发送原始 pcaket,您可以使用Pcap.Net。它是用 C++/CLI 和 C# 编写的 WinPcap 包装器,包括数据包解释和创建框架。

回答by Erich Mirabal

I've not tried this, but I know that WinPCap allows you to do a raw send. Since it works at a pretty low level, it might allow you to send low enough on the stack to bypass the full broadcast. There are various C# wrappers out there, and of course you can use the normal C/C++ code available out there. I think the trick might be to bind to the right adapter you want to send out of and it might just work.

我没有试过这个,但我知道 WinPCap 允许你做一个原始的send。由于它在相当低的级别上工作,因此它可能允许您在堆栈上发送足够低的数据以绕过完整广播。那里有各种 C# 包装器,当然您可以使用那里可用的普通 C/C++ 代码。我认为诀窍可能是绑定到您想要发送出去的正确适配器,它可能会起作用。

回答by JimB

The broadcast address 255.255.255.255 is too general.You have to craft a different broadcast address for each network interface separately.

广播地址 255.255.255.255 太笼统了。您必须分别为每个网络接口制作不同的广播地址。