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

标签 c# .net asp.net asp.net-mvc vb.net

我尝试了书中的所有技巧,创建一个新对象,实例化它(即使它说我不能)并尝试创建一个引用来使用它,然后还尝试调用其中的 .Address 值它在使用它时就像我会使用共享成员(没有实例化)并且没有任何工作,msdn 示例/帮助是无用的......我什至尝试继承它并像那样使用它,它们都没有工作,我确定我是缺少一些东西,任何人都可以给我一些代码示例吗?这是关于它的 msdn 文档,给你一个概述......

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

虽然我更喜欢 vb.net,但我可以用 c# 和 vb.net 阅读和编码,所以两者都可以。

谢谢:)

旁白:如果有人想知道为什么,我只是想从电脑上获取我的路由器名称/标签,如下所示... How to get Router Name & IP as shown in Windows Network Tab? (in Code)

最佳答案

来自 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();
        }
    }
}

关于c# - 我如何使用 System.Net.NetworkInformation.GatewayIPAddressInformation 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3840195/

相关文章:

c# - 正则表达式:命名组和替换

asp.net - ASP.NET 应用程序的国际化

c# - 允许将空值添加到列表

c# - 当 .Net Thread 没有名称时,如何使用 NLog 打印 threadid 而不是 threadname?

c# - 即使只有一项,也会触发两项任务,使用 async/await 和 Task.WhenAll

asp.net - 使用 NuGet 的 SignalR 问题

c# - 我如何重定向到另一个传递数据但没有 C# 帖子的页面

c# - Visual Basic "Module not Found"错误

c# - 通缉 : List of data following certain rules concerning dates

c# - 如何在 C# 中将窗体居中