简体   繁体   English

没有 C# 中的 IP 地址和 Ping 方法,如何检查 PC 是否与 Internet 或 Intranet 连接?

[英]How to check PC is connected with Internet or Intranet without IP address and Ping method in C#?

How can I check PC is Connected with Intranet or Internet without using Ping method and IP address in C#?如何在不使用 Ping 方法和 C# 中的 IP 地址的情况下检查 PC 是否与 Intranet 或 Internet 连接?

For my use case, I needed to have a service up in a LAN network and check Network status from time to time.对于我的用例,我需要在 LAN 网络中启动服务并不时检查网络状态。 I eventually used this:我最终使用了这个:

static readonly INetworkListManager NetworkListManager = new NetworkListManager();
// ...
while (NetworkListManager.IsConnected) {
  // do something...
}

// loop is over. no internet!
while (!NetworkListManager.IsConnected) {
  // wait for reconnection...
}

In my case that achieved what I needed, and with some testing it also worked on my WAN environment.就我而言,它实现了我所需要的,并且经过一些测试,它也适用于我的 WAN 环境。 But as always, there's no 100% correct assumption when it comes to interacting with other hardware.但与往常一样,在与其他硬件交互时,没有 100% 正确的假设。 Incorrect result can happen , so put in as much as test you can.可能会出现不正确的结果,因此请尽可能多地进行测试。

Here's something i used for a game of mine to detect if there is a network connection without it even touching or talking the router or other devices:这是我在我的游戏中使用的东西,用于检测是否存在网络连接,甚至无需触摸或与路由器或其他设备通话:

// Recommended for clean code
public static bool InternetConnection() => System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

The code above is just the same as:上面的代码与以下代码相同:

public static bool InternetConnection() { 
    return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM