查找本地PC的子网掩码

时间:2015-01-08 11:54:00

标签: c# ip subnet

我在尝试从本地PC上获取某些子网信息时遇到了一些困难。这段代码"技术上"运行正常,因为它不包含任何警告或错误,但是当运行应用程序时,返回的所有内容都是" 0.0.0.0"我的应用程序中有其他非常相似的代码,请求IP地址,默认网关等,并且完全正常,所以我现在不知道为什么这不会返回子网掩码。任何帮助,将不胜感激!是否有一些非常明显的东西我错过了哪个是为什么这不起作用?

        NetworkInterface[] subnetInterface = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface subnetMask in subnetInterface)
        {
            UnicastIPAddressInformationCollection UnicastIPInfoCol = subnetMask.GetIPProperties().UnicastAddresses;
            foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol)
            {
                subnetMaskLabel.Content = UnicatIPInfo.IPv4Mask;

            }

我有3个网络适配器,2个VMWare当前为此应用程序而禁用,1个本地连接已启用,因此应用程序仅审查该连接。

更新 我试图解决获得" 255.0.0.0"并没有成功。当我在我的应用程序中放置断点时,信息在" subnetMaskLabel.Content = UnicatIPInfo.IPv4Mask;"语法存储的值是正确的子网掩码,但它显示的是不正确的,有关如何解决这个问题的想法吗?

1 个答案:

答案 0 :(得分:2)

您可能正在查看非ipv4地址。试试这个网络地址:

    public static void GetSubnetMask()
    {
        foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
        {
            foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
            {
                if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
                {
                    Console.WriteLine(unicastIPAddressInformation.IPv4Mask);
                }
            }
        }
    }