我如何使用System.Net.NetworkInformation.GatewayIPAddressInformation类?

Erx*_*der 4 .net c# vb.net asp.net asp.net-mvc

我尝试了书中的每一个技巧,创建了一个新对象,实例化它(即使它说我不能)并且只是尝试创建一个使用它的引用,然后还尝试在使用它时调用它内部的.Address值它就像我会使用一个共享成员(没有实例化),没有任何工作,msdn示例/帮助是无用的...我甚至尝试继承它并使用它,没有一个工作,我相信我错过了什么,任何人都可以给我一些代码示例吗?这里有msdn文档给你一个概述......

http://msdn.microsoft.com/en-us/library/system.net.networkinformation.gatewayipaddressinformation.aspx

虽然我喜欢vb.net,但我可以在c#和vb.net中阅读和编码,所以要么一切都会好的.

谢谢:)

旁白:如果有人想知道为什么,我只是试图从这里显示的PC上获取我的路由器名称/标签... 如何获取路由器名称和IP,如Windows网络选项卡中所示?(代码中)

abe*_*nky 8

来自MSDN:

  • 简而言之,您可以调用NetworkInterface.GetAllNetworkInterfaces()一组适配器.
  • 在其中一个适配器上,得到adapter.GetIPProperties().GatewayAddresses.
  • 每个元素GatewayAddresses都是一个GatewayIPAddressInformation.

public static void DisplayGatewayAddresses()
{
    Console.WriteLine("Gateways");
    NetworkInterface[] adapters  = NetworkInterface.GetAllNetworkInterfaces();
    foreach (NetworkInterface adapter in adapters)
    {
        IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
        GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses;
        if (addresses.Count >0)
        {
            Console.WriteLine(adapter.Description);
            foreach (GatewayIPAddressInformation address in addresses)
            {
                Console.WriteLine("  Gateway Address ......................... : {0}", 
                    address.Address.ToString());
            }
            Console.WriteLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)