您可以为此目的使用Network List Manager API ,从 C# import Network List Manager Type Library 中使用它(直接编译下面的示例,取消选中 Embed interop types in reference properties)。
然后你必须枚举所有连接的网络,因为可能不止一个,例如现在我连接到互联网和 VPN。然后对于所有连接的网络调用GetCategory() API,它返回NLM_NETWORK_CATEGORY(私有、公共或域)。
这是示例代码:
var manager = new NetworkListManagerClass();
var connectedNetworks = manager.GetNetworks(NLM_ENUM_NETWORK.NLM_ENUM_NETWORK_CONNECTED).Cast<INetwork>();
foreach (var network in connectedNetworks)
{
Console.Write(network.GetName() + " ");
var cat = network.GetCategory();
if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PRIVATE)
Console.WriteLine("[PRIVATE]");
else if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_PUBLIC)
Console.WriteLine("[PUBLIC]");
else if (cat == NLM_NETWORK_CATEGORY.NLM_NETWORK_CATEGORY_DOMAIN_AUTHENTICATED)
Console.WriteLine("[DOMAIN]");
}
Console.ReadKey();
对于网络发现,您必须使用防火墙 API 并参考 COM 库 NetFwTypeLib 并获取INetFwProfile以获取活动配置文件,然后在服务中有文件共享、网络发现和远程桌面服务,如果这些服务已启用,则有一个布尔标志。这是示例代码:(只是警告你我没有在生产中使用下面的代码我只是在探索这个 API)
Type objectType = Type.GetTypeFromCLSID(new Guid("{304CE942-6E39-40D8-943A-B913C40C9CD4}"));
var man = Activator.CreateInstance(objectType) as INetFwMgr;
/// get current profile
INetFwProfile prof = man.LocalPolicy.CurrentProfile;
Console.WriteLine("Current profile ");
ShowProfileServices(prof);
以及显示配置文件服务的方法。
private static void ShowProfileServices(INetFwProfile prof)
{
var services = prof.Services.Cast<INetFwService>();
var sharing = services.FirstOrDefault(sc => sc.Name == "File and Printer Sharing");
if (sharing != null)
Console.WriteLine(sharing.Name + " Enabled : " + sharing.Enabled.ToString());
else
Console.WriteLine("No sharing service !");
var discovery = services.FirstOrDefault(sc => sc.Name == "Network Discovery");
if (discovery != null)
Console.WriteLine(discovery.Name + " Enabled : " + discovery.Enabled.ToString());
else
Console.WriteLine("No network discovery service !");
var remoteDesktop = services.FirstOrDefault(sc => sc.Name == "Remote Desktop");
if (remoteDesktop != null)
Console.WriteLine(remoteDesktop.Name + " Enabled : " + remoteDesktop.Enabled.ToString());
else
Console.WriteLine("No remote desktop service !");
}