如何使用c#在Windows中检测网络位置类型

本文关键字:检测 网络 位置 置类型 Windows 何使用 | 更新日期: 2023-09-27 18:12:07

我正在使用c#编写一个Windows应用程序,我需要检测网络位置类型。

当你将Windows机器连接到网络(有线或无线)时,它将尝试识别网络,然后将其分类为公共,私有等。我想以编程的方式做同样的事情使用我的应用程序。我怎么做呢?

如果需要更多的细节,请让我知道。谢谢你。

如何使用c#在Windows中检测网络位置类型

您需要做两件事:

  • 解析本地机器的IP地址。这本身就是一个挑战,因为通常机器会有几个IP地址。它可以同时使用多个IP。IP地址可以(并且正在)动态更改

  • 检查IP地址是否在私网范围内。查看这个答案的链接和更多信息。实际上,每个私有地址只能在本地网络(局域网)内路由可达。不可能从外部连接到私有地址。如果机器想要与外界通话,它使用网关机器。网关机器记住请求来自何处(私有IP),将其转换为公共IP并解析反向响应。

  you networkinterface to get the network information  
  NetworkInterface[] interfaces =  NetworkInterface.GetAllNetworkInterfaces();

  it has many properties and the output showing infornt of that
  NetworkInterface[0].Description:  Intel(R) 82579LM Gigabit Network Connection
  NetworkInterface[0].ID: {xxxxxxxxxx-0322-466Fxxx-xxxxxxxxxx}
  NetworkInterface[0].Name: Ethernet
  NetworkInterface[0].Interface Type: Ethernet
  NetworkInterface[0].Operational Status: Down
  NetworkInterface[0].Speed: -1
  NetworkInterface[0].Supports Multicast: True