在 C# 中检测网络状态(连接 - 断开连接)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/936027/
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
Detecting network state (connected - disconnected) in C#
提问by Bobby Cannon
I am in need of a piece of code that can detect if a network connection is connected or disconnected. The connected state would mean a cable was plugged into the Ethernet connection. A disconnected state would mean there is not cable connected.
我需要一段代码来检测网络连接是连接还是断开。连接状态意味着电缆已插入以太网连接。断开连接状态意味着没有连接电缆。
I can't use the WMI interface due to the fact that I'm running on Windows CE. I don't mind invoking the Win32 API but remember that I'm using Windows CE and running on the Compact Framework.
由于我在 Windows CE 上运行,我无法使用 WMI 界面。我不介意调用 Win32 API,但请记住,我使用的是 Windows CE 并在 Compact Framework 上运行。
采纳答案by Dana Holt
Check out this MSDN article:
查看这篇 MSDN 文章:
Testing for and Responding to Network Connections in the .NET Compact Framework
回答by Joel Coehoorn
One thing to remember is that a network connection is notequal to an internet connection.
要记住的一件事是网络连接不等于互联网连接。
It sounds like you already get that because you define connected as meaning "a cable is plugged into the Ethernet connection", but it bears repeating.
听起来您已经明白了这一点,因为您将连接定义为“将电缆插入以太网连接”,但需要重复一遍。
回答by Tom van Enckevort
Call GetAdaptersInfoand loop through the list of available network adapters until you find the one you're looking for?
调用GetAdaptersInfo并遍历可用网络适配器列表,直到找到您要找的适配器?
回答by ctacke
The easiest way is to use OpenNETCF's SDFand look at the OpenNETCF.Net.NetworkInformation.NetworkInterfaceWatcher class, which will raise events when NDIS sends out notifications (like MEDIA_CONNECT and MEDIA_DISCONNECT).
最简单的方法是使用OpenNETCF 的 SDF并查看OpenNETCF.Net.NetworkInformation.NetworkInterfaceWatcher 类,它会在 NDIS 发出通知(如 MEDIA_CONNECT 和 MEDIA_DISCONNECT)时引发事件。
You can do the same work without the SDF, of course. It involves onening the NDIS driver directly and calling IOCTL_NDISUIO_REQUEST_NOTIFICATIONwith a P2P message queue handle. It's not overly difficult, but there's a lot you have to get right for it to work and not leak.
当然,您可以在没有 SDF 的情况下完成相同的工作。它涉及直接对 NDIS 驱动程序进行处理,并使用 P2P 消息队列句柄调用IOCTL_NDISUIO_REQUEST_NOTIFICATION。这并不太难,但是您必须做很多事情才能使其正常工作并且不会泄漏。