gpt4 book ai didi

c# - 获取网络接口(interface)连接到的网络名称

转载 作者:行者123 更新时间:2023-12-02 09:22:10 24 4
gpt4 key购买 nike

在 Windows 控制面板中,您可以找到显示以下内容的网络接口(interface)/连接列表:

network interfaces

在 .NET 框架中,这些在 NetworkInterface 类中表示(通过 NetworkInterface.GetAllNetworkInterfaces 找到)。

作为引用,假设我正在从以太网接口(interface)读取属性 - NetworkInterface.Name 属性返回 “Ethernet”NetworkInterface.Description code> 属性返回“Realtek PCIe FE 系列 Controller ”

但是,类中的任何内容似乎都无法让我获得它所连接的网络的名称(在本例中为“BELL024”)。我该如何得到那根绳子?我必须知道该接口(interface)与哪个网络关联,而不仅仅是现有网络的列表。

最佳答案

事实证明,有关每个网络的信息都被 Windows 存储为“网络配置文件”,存储其名称和其他信息,例如是否公开。用户可以在控制面板中更改名称,但在我的情况下这不是问题。

Microsoft 的Windows API 代码包包含获取网络配置文件集合所需的 API。由于它包含大量我不需要的臃肿内容,因此包装 Windows API 的最低限度代码 can be found here .

然后可以像这样找到网络配置文件的集合:

//Get the networks that are currently connected to
var networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);

集合中的每个对象都代表一个网络配置文件,并包含 NetworkConnection 对象的集合。每个 NetworkConnection 对象似乎都是有关接口(interface)与基础网络的连接的信息。

foreach(Network network in networks)
{
//Name property corresponds to the name I originally asked about
Console.WriteLine("[" + network.Name + "]");

Console.WriteLine("\t[NetworkConnections]");
foreach(NetworkConnection conn in network.Connections)
{
//Print network interface's GUID
Console.WriteLine("\t\t" + conn.AdapterId.ToString());
}
}

NetworkConnection.AdapterId 属性与 NetworkInterface.Id 属性所知道的网络接口(interface) GUID 相同。

因此,您可以通过检查网络连接之一是否与接口(interface)具有相同的 ID 来确定接口(interface)连接到哪个网络。请注意,它们的表示方式不同,因此您需要做更多的工作:

example image

在上面的示例中,我的 Wi-Fi 和以太网接口(interface)都连接到 BELL024 网络。

关于c# - 获取网络接口(interface)连接到的网络名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41943945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com