[英]Get name of network that a network interface is connected to
在Windows控制面板中,您可以找到顯示以下內容的網絡接口/連接列表:
在.NET框架中,它們在NetworkInterface
類中表示(並通過NetworkInterface.GetAllNetworkInterfaces
找到)。
作為參考,說我正在從以太網接口讀取屬性NetworkInterface.Name
屬性返回"Ethernet"
, NetworkInterface.Description
屬性返回"Realtek PCIe FE Family Controller"
。
但是,該類中似乎沒有任何內容可以讓我知道它所連接的網絡的名稱(在本例中為"BELL024"
)。 我將如何獲取該字符串? 我必須知道接口與哪個網絡相關聯,而不僅是現有網絡的列表。
事實證明,有關每個網絡的信息都由Windows作為“網絡配置文件”存儲,並存儲其名稱和其他信息(如是否公開)。 用戶可以在控制面板中更改名稱,但就我而言,這不是問題。
Microsoft的Windows API代碼包包含獲取網絡配置文件所需的API。 由於它包含了很多我不需要的膨脹, 因此可以在此處找到包裝Windows API的最基本代碼。
然后可以找到網絡配置文件的集合,如下所示:
//Get the networks that are currently connected to
var networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.Connected);
集合中的每個對象代表一個網絡配置文件,並包含一個NetworkConnection
對象的集合。 每個NetworkConnection
對象似乎都是有關接口與基本網絡的連接的信息。
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
屬性知道的相同網絡接口GUID。
因此,可以通過檢查網絡連接之一是否具有與該接口相同的ID來確定接口連接到哪個網絡。 請注意,它們的表示方式有所不同,因此您需要做更多的工作:
在上面的示例中,我的Wi-Fi和以太網接口都連接到BELL024網絡。
您可以使用WMI查詢您的網絡名稱。 您可以使用以下代碼作為示例:
ManagementScope oMs = new ManagementScope();
ObjectQuery oQuery =
new ObjectQuery("Select * From Win32_NetworkAdapter");
ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
ManagementObjectCollection oReturnCollection = oSearcher.Get();
foreach (ManagementObject oReturn in oReturnCollection)
{
if (oReturn.Properties["NetConnectionID"].Value != null)
{
Console.WriteLine("Name : " + oReturn.Properties["NetConnectionID"].Value);
}
}
在Windows 8和Windows 2012及更高版本上,您可以從root / StandardCimv2命名空間查詢WMI類MSFT_NetConnectionProfile 。
將其轉換為C#並不難。
Get-WmiObject -Namespace root/StandardCimv2 -Class MSFT_NetConnectionProfile | Format-Table InterfaceAlias, Name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.