65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 System.Net.NetworkInformation 命名空间中定义的 API

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (1投票)

2009年12月31日

CPOL

2分钟阅读

viewsIcon

25395

本文使用 C# 演示如何收集网络信息。

获取网络信息

使用 System.Net.NetworkInformation 命名空间中定义的 API

有时你需要获取周围网络的一些总体信息。在 C# 中编写代码时,你可以使用在 System.Net.NetworkInformation 命名空间中定义的许多 API。这些 API 使你可以查询网络接口卡 (NIC) 状态、当前网络流量、DNS 和 IP 地址信息,甚至可以 ping 远程服务器。本文参考了 MSDN 和 Professional .NET Framework 2.0,提供了可以用来查询网络设备信息和状态的小程序,以及查询该网络流量中的 IPv4 地址。这对于安全目的可能很有用。路由器用于路由数据包——它对这些数据包中包含的数据不感兴趣。但它必须执行地址解析协议。如果 IP 号码在对回复的 ARP 请求后已被缓存,那么该 32 位 IP 号码必须与目标机器的 48 位 MAC 号码相关联。IP 号码和 MAC 号码之间不仅没有数学关系,而且也没有办法验证 IP 的来源。除非已知且预期的 IP 地址显式写入路由器的磁盘,否则它们会被更多传入的地址覆盖。但在敲响安全警钟之前,我们只是编写一些代码来告知我们活动情况。

using System;
using System.Net;
using System.Net.NetworkInformation;
public sealed class Program {
public static void Main() {
DisplayUnicastAddresses();
}

public static void DisplayUnicastAddresses()
{
    Console.WriteLine("Unicast Addresses");
    NetworkInterface[] adapters  = NetworkInterface.GetAllNetworkInterfaces();
    foreach (NetworkInterface adapter in adapters)
    {
        IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
        UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses;
        if (uniCast.Count >0)
        {
            Console.WriteLine(adapter.Description);
            string lifeTimeFormat = "dddd, MMMM dd, yyyy  hh:mm:ss tt";
            foreach (UnicastIPAddressInformation uni in uniCast)
            {
                DateTime when;

                Console.WriteLine
		("  Unicast Address ......................... : {0}", uni.Address);
                Console.WriteLine
		("     Prefix Origin ........................ : {0}", uni.PrefixOrigin);
                Console.WriteLine
		("     Suffix Origin ........................ : {0}", uni.SuffixOrigin);
                Console.WriteLine
		("     Duplicate Address Detection .......... : {0}", 
                    uni.DuplicateAddressDetectionState);

                // Format the lifetimes as Sunday, February 16, 2003 11:33:44 PM
                // if en-us is the current culture.

                // Calculate the date and time at the end of the lifetimes.    
                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressValidLifetime);
                when = when.ToLocalTime();    
                Console.WriteLine("     Valid Life Time ...................... : {0}", 
                    when.ToString(lifeTimeFormat,
			System.Globalization.CultureInfo.CurrentCulture)
                );
                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressPreferredLifetime);   
                when = when.ToLocalTime();
                Console.WriteLine("     Preferred life time .................. : {0}", 
                    when.ToString(lifeTimeFormat,
			System.Globalization.CultureInfo.CurrentCulture)
                ); 

                when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime);
                when = when.ToLocalTime(); 
                Console.WriteLine("     DHCP Leased Life Time ................ : {0}", 
                    when.ToString(lifeTimeFormat,
			System.Globalization.CultureInfo.CurrentCulture)
                );
            }
            Console.WriteLine();
        }
    }
  }
}

输出显示配置正常。路由器没有转储其 ARP 缓存,因此似乎没有攻击者发送伪造的 ARP 请求来污染我们的缓存。这是输出:

Unicast Addresses
Intel(R) Wireless WiFi Link 4965AGN
  Unicast Address ......................... : fe80::6932:849e:6838:35c8%12
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:42 AM
  Unicast Address ......................... : 192.168.1.101
     Prefix Origin ........................ : Dhcp
     Suffix Origin ........................ : OriginDhcp
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Thursday, December 31, 2009  08:42:39 PM
     Preferred life time .................. : Thursday, December 31, 2009  08:42:39 PM
     DHCP Leased Life Time ................ : Friday, January 01, 2010  12:24:09 AM

Bluetooth Device (Personal Area Network)
  Unicast Address ......................... : fe80::98f6:cced:c44a:d8ad%10
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Deprecated
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:49 AM
  Unicast Address ......................... : 169.254.216.173
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Tentative
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:42 AM

Generic Marvell Yukon Chipset based Ethernet Controller
  Unicast Address ......................... : fe80::a1ce:c8bd:9784:a08b%8
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Deprecated
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:57 AM
  Unicast Address ......................... : 169.254.160.139
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Tentative
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:50 AM

Software Loopback Interface 1
  Unicast Address ......................... : ::1
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:06:10 AM
  Unicast Address ......................... : 127.0.0.1
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : WellKnown
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:06:10 AM

isatap.{EABD2F31-7318-43F3-B16F-F3F6589369E1}
  Unicast Address ......................... : fe80::5efe:192.168.1.101%16
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Deprecated
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:35 AM

Teredo Tunneling Pseudo-Interface
  Unicast Address ......................... : 2001:0:4137:9e50:1857:4cd:3f57:fe9a
     Prefix Origin ........................ : RouterAdvertisement
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:03 AM
  Unicast Address ......................... : fe80::1857:4cd:3f57:fe9a%13
     Prefix Origin ........................ : WellKnown
     Suffix Origin ........................ : LinkLayerAddress
     Duplicate Address Detection .......... : Preferred
     Valid Life Time ...................... : Sunday, February 06, 2146  06:52:25 AM
     Preferred life time .................. : Sunday, February 06, 2146  06:52:25 AM
     DHCP Leased Life Time ................ : Thursday, December 31, 2009  04:05:03 AM

这里有一些查询同一网络中 IPv4 地址的代码:

using System;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
public sealed class Application {
public static void Main() {
DisplayIPv4NetworkInterfaces();
}
public static void DisplayIPv4NetworkInterfaces()
{
    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
    IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
    Console.WriteLine("IPv4 interface information for {0}.{1}",
       properties.HostName, properties.DomainName);
    Console.WriteLine();   

    foreach (NetworkInterface adapter in nics)
    {
        // Only display information for interfaces that support IPv4.
        if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false)
        {
            continue;
        }
        Console.WriteLine(adapter.Description);
        // Underline the description.
        Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length,'='));
        IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
        // Try to get the IPv4 interface properties.
        IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties();

        if (p == null)
        {
            Console.WriteLine("No IPv4 information is available for this interface.");
            Console.WriteLine();
            continue;
        }
        // Display the IPv4 specific data.
        Console.WriteLine("  Index ............................. : {0}", p.Index);
        Console.WriteLine("  MTU ............................... : {0}", p.Mtu);
        Console.WriteLine("  APIPA active....................... : {0}", 
            p.IsAutomaticPrivateAddressingActive);
        Console.WriteLine("  APIPA enabled...................... : {0}", 
            p.IsAutomaticPrivateAddressingEnabled);
        Console.WriteLine("  Forwarding enabled................. : {0}", 
            p.IsForwardingEnabled);
        Console.WriteLine("  Uses WINS ......................... : {0}", 
            p.UsesWins);
        Console.WriteLine();
    }
 }
}

以上产生:

IPv4 interface information for John-PC.

Intel(R) Wireless WiFi Link 4965AGN
===================================
  Index ............................. : 12
  MTU ............................... : 1500
  APIPA active....................... : False
  APIPA enabled...................... : True
  Forwarding enabled................. : False
  Uses WINS ......................... : False

Bluetooth Device (Personal Area Network)
========================================
  Index ............................. : 10
  MTU ............................... : 1500
  APIPA active....................... : False
  APIPA enabled...................... : True
  Forwarding enabled................. : False
  Uses WINS ......................... : False

Generic Marvell Yukon Chipset based Ethernet Controller
=======================================================
  Index ............................. : 8
  MTU ............................... : 1500
  APIPA active....................... : False
  APIPA enabled...................... : True
  Forwarding enabled................. : False
  Uses WINS ......................... : False

Software Loopback Interface 1
=============================
No IPv4 information is available for this interface.

isatap.{71A2BA2A-7090-4221-BFAB-25FAEF97756D}
=============================================
No IPv4 information is available for this interface.

isatap.{1F7410AD-675A-4507-8E32-58E279C1DAFB}
=============================================
No IPv4 information is available for this interface.

isatap.{EABD2F31-7318-43F3-B16F-F3F6589369E1}
=============================================
No IPv4 information is available for this interface.

Teredo Tunneling Pseudo-Interface
=================================
No IPv4 information is available for this interface.

如果有人决定完全部署 IPv6,这些基本信息将会有所帮助。那将是一次非常强大的迁移。

© . All rights reserved.