网卡信息检测与网络流量检测

网卡信息检测与网络流量检测

​ 每台计算机进行网线通讯,都要借助一个硬件设备,网卡,简称NICNICNetwork Interface Controller 的缩写。网卡则负责将比特流转换成电信号发送出去和将检测到的电信号转换成比特流并接收。

网络适配器:

  • 又称网卡是连接计算机与网络的硬件设备。

  • 整理计算机上发往网线上的数据,并将数据分解为适当大小的数据包之后向网络上发送。

    在C#中,提供了System.Net.NetworkInformation命名空间,来提供网卡的相关信息。

其中包括:

  • 对本机网卡相关信息的检测
  • 本机有多少网卡,网卡名称、速度、硬件地址等。
  • 对本机网络流量的检测
    • 网络连接配置、接收与发送的数据包等。

网卡信息检测相关类

Network Interface类

提供了网络适配器的配置和统计信息:

  • 网络适配器个数

  • 网络适配器型号

  • 网络适配器的速度

  • 网络适配器MAC地址

  • 网络适配器连接是否可用

每个网络适配器都包含一个NetworkInterface对象与之对应。

属性及方法 说明
Name属性 获取网络适配器的名称
Speed属性 获取网络适配器的速度(bit/秒)
GetAllNetworkInterfaces方法 返回描述本地计算机上的所有网络适配器对象
GetIPProperties方法 返回描述此网络适配器配置的对象
GetIsNetworkAvailable方法 指示是否有任何可用的网络连接
GetPhysicalAddress方法 返回此适配器的媒体访问控制(MAC)地址
Supports方法 指示接口是否支持指定的协议(IPv4或IPv6)

获取网卡的信息

 private static void NetworkInterfaces()
        {
            #region NetWorkInterface
            //利用NetworkInterface类提供的静态方法得到NetworkInterface类型的数组。
            NetworkInterface[] networkInterface = NetworkInterface.GetAllNetworkInterfaces();//声明并初始化了一个 NetworkInterface类的对象数组。
            Console.WriteLine($"网络适配器的个数为:{networkInterface.Length}");
            Console.WriteLine($"是否有可以用网络连接:{NetworkInterface.GetIsNetworkAvailable()}");
            Console.WriteLine();
            foreach (NetworkInterface network in networkInterface)
            {
                Console.WriteLine($"网卡名字:{network.Name}");
                Console.WriteLine($"物理地址:{network.GetPhysicalAddress()}");
                Console.WriteLine($"速度:{network.Speed}");
                Console.WriteLine($"网卡ID:{network.Id}");
                Console.WriteLine($"网卡描述:{network.Description}");

                Console.WriteLine($"是否仅接受数据包:{network.IsReceiveOnly}");
                Console.WriteLine($"是否支持IPV4:{network.Supports(NetworkInterfaceComponent.IPv4)}");
                Console.WriteLine($"是否支持IPV6:{network.Supports(NetworkInterfaceComponent.IPv6)}");
                Console.WriteLine("-----------------------------------------------------------------");

            }
网卡名字:本地连接* 1
物理地址:144F8A2158EB
速度:-1
网卡ID:{FA9901D2-C3AD-412B-BCC2-D6FF592EE29B}
网卡描述:Microsoft Wi-Fi Direct Virtual Adapter
是否仅接受数据包:False
是否支持IPV4:True
是否支持IPV6:True

IPInterfaceProperties类

  • 检测本机所有网络适配器支持的各种地址

    • Dns服务器的IP地址、网关地址以及多路广播地址。
  • IPInterfaceProperties类是抽象类,不能实例化。

    • 通过NetworkInterface对象的GetIPProperties()获得其实例

IPInterfaceProperties类常用的属性和方法

属性及方法 说明
AnycastAddresses属性 获取分配给此接口的任意广播IP地址
DhcpServerAddresses属性 获取此接口的动态主机配置协议(DHCP)服务器的地址
DnsAddresses属性 获取此接口的域名系统(DNS)服务器的地址
DnsSuffix属性 获取与此接口关联的域名系统(DNS)后缀
GatewayAddresses属性 获取此接口的网关地址
MulticastAddresses属性 获取分配给此接口的多路广播地址
UnicastAddresses属性 获取分配给此接口的单播地址
GetIPv4Properties方法 获取此网络接口的Internet协议版本(IPv4)配置数据
GetIPv6Properties方法 获取此网络接口的Internet协议版(IPv6)配置数据

实例 网卡单播地址的信息

 private static void GetUnicastAdress()
        {
            #region UnicastAddress 网络接口的单播地址
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                IPInterfaceProperties iPInterfaceProperties = adapter.GetIPProperties();
                UnicastIPAddressInformationCollection unicasts = iPInterfaceProperties.UnicastAddresses;
                //定义时间格式
                //dddd 周几
                //mmmm 月份
                //yyyy 年份
                //dd   几日
                //hh:mm:ss 时分秒
                // tt  上下午
                string timetype = "dddd, MMMM dd, yyyy  hh: mm: ss tt";//自己定义时间的格式
                if (unicasts.Count > 0)
                {
                    Console.WriteLine(adapter.Description);//打印出网卡的描述
                    foreach (UnicastIPAddressInformation unicastIPAddressInformation in unicasts)
                    {
                        DateTime when;//声明一个当前时间的日期变量

                        Console.WriteLine("单播地址:.................{0}", unicastIPAddressInformation.Address);
                        Console.WriteLine("获取IPv4子网掩码:.........{0}", unicastIPAddressInformation.IPv4Mask);
                        Console.WriteLine("此地址作为首选地址的秒数...{0}", unicastIPAddressInformation.AddressPreferredLifetime);
                        Console.WriteLine("此地址的有效剩余秒数:.....{0}", unicastIPAddressInformation.AddressValidLifetime);
                        Console.WriteLine("DHCP剩余时间:.............{0}", unicastIPAddressInformation.DhcpLeaseLifetime);
                        Console.WriteLine("前缀的长度:...............{0}", unicastIPAddressInformation.PrefixLength);
                        Console.WriteLine("标识前缀的值:.............{0}", unicastIPAddressInformation.PrefixOrigin);
                        Console.WriteLine("标识后缀的值:.............{0}", unicastIPAddressInformation.SuffixOrigin);
                        when = DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddressInformation.AddressPreferredLifetime);//计算时间
                        when.ToLocalTime();//转化为本地时间
                        Console.WriteLine("此地址作为首选地址的到期时间为......{0}",
                            when.ToString(timetype, System.Globalization.CultureInfo.CurrentCulture));//当地时间格式
                        when = DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddressInformation.AddressValidLifetime);//计算时间
                        when.ToLocalTime();//转化为本地时间
                        Console.WriteLine("此地址的到期时间为..................{0}",
                            when.ToString(timetype, System.Globalization.CultureInfo.CurrentCulture));//当地时间格式

                        when = DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddressInformation.DhcpLeaseLifetime);//计算时间
                        when.ToLocalTime();//转化为本地时间
                        Console.WriteLine("DHCP到期时间为.......................{0}",
                            when.ToString(timetype, System.Globalization.CultureInfo.CurrentCulture));//当地时间格式

                    }
                }
            }
            Console.ReadLine();

获取网关地址

 private static void GatewayAddress()
        {
            #region IPInterfaceProperties 
            NetworkInterface[] adapterd = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface networkInterface in adapterd)
            {
                IPInterfaceProperties iPInterfaceProperties = networkInterface.GetIPProperties();
                //网关信息
                GatewayIPAddressInformationCollection gatewayIPAddressInformation = iPInterfaceProperties.GatewayAddresses;
                foreach (var item in gatewayIPAddressInformation)
                {
                    Console.WriteLine($"网关地址:..............{gatewayIPAddressInformation[0].Address }");
                    Console.WriteLine();
                }



            }
            Console.ReadLine();

获取任意广播地址

  private static void AnyCastAddress()
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var adapter in adapters)
            {
                IPInterfaceProperties iPInterfaceProperties = adapter.GetIPProperties();
                IPAddressInformationCollection iPAddressInformation = iPInterfaceProperties.AnycastAddresses;
                if (iPAddressInformation.Count > 0)
                {
                    foreach (var i in iPAddressInformation)
                    {
                        Console.WriteLine($"广播地址为:..........i.Address");
                        Console.WriteLine($"是否在DNS服务器中出现:..........{(i.IsDnsEligible ? "是" : "否")}");//注意此处条件表达式的用法
                        Console.WriteLine($"广播地址为:..........{(i.IsTransient ? "是" : "否")}");
                    }
                }
                else
                {
                    Console.WriteLine("{0}不存在广播地址", adapter.Name);
                }
            }
            Console.ReadLine();
        }

获取此接口的动态主机配置协议(DHCP)服务器的地址

private static void DhcpserverIPAddress()
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var adapter in adapters)
            {
                IPInterfaceProperties iPInterfaceProperties = adapter.GetIPProperties();
                IPAddressCollection iPAddressInformation = iPInterfaceProperties.DhcpServerAddresses;
                if (iPAddressInformation.Count > 0)
                {
                    foreach (var i in iPAddressInformation)
                    {
                        Console.WriteLine($"广播地址为:..........{i.Address}");

                    }
                    Console.ReadLine();
                }

            }
        }

获取此接口的域名系统(DNS)服务器的地址

 private static void DnsSeverAddress()
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var adapter in adapters)
            {
                IPInterfaceProperties iPInterfaceProperties = adapter.GetIPProperties();
                IPAddressCollection dnsServers = iPInterfaceProperties.DnsAddresses;
                if (dnsServers.Count > 0)
                {
                    Console.WriteLine(adapter.Description);
                    foreach (var i in dnsServers)
                    {
                        Console.WriteLine($"dns服务器地址为:..........{i.ToString()}");

                    }

                }

            }
            Console.ReadLine();
        }

获取此网络接口的Internet协议版本(IPv4)配置数据

 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 informatin for interfaces that support IPv4.
                if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false)//判断是否支持IPV4
                {
                    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();
            }
        }

对齐方式的小技巧

 private static void printFenge()
        {
            string a = "1234567890";
            Console.WriteLine(a);
            Console.WriteLine(String.Empty.PadLeft(a.Length, '='));
            Console.WriteLine(String.Empty.PadLeft(a.Length, '*'));
            Console.WriteLine(String.Empty.PadRight(a.Length, 'n'));
        }

网络流量检测类

IPGlobalProperties类

  • 提供了本地计算机网络连接和通信统计数据的信息。
    • 接收到的数据包个数、丢弃的数据包个数等。

IPGlobalProperties类提供的常用方法

名 称 说 明
GetActiveTcpConnections 返回有关本地计算机上的 Internet协议版本 4 (IPV4) 传输控制协议 (TCP) 连接的信息
GetActiveTcpListeners 返回有关本地计算机上的 Internet 协议版本 4 (IPV4) 传输控制协议 (TCP) 侦听器的终结点信息
GetActiveUdpListeners 返回有关本地计算机上的 Internet 协议版本 4 (IPv4) 用户数据报协议 (UDP) 侦听器的信息
GetIPv4GlobalStatistics 提供本地计算机的 Internet 协议版本 4 (IPv4) 统计数据
GetIPv6GlobalStatistics 提供本地计算机的 Internet 协议版本 6 (IPv6) 统计数据
GetTcpIPv4Statistics 提供本地计算机的传输控制协议/Internet 协议版本 (TCP/IPv4) 统计数据
GetTcpIPv6Statistics 提供本地计算机的传输控制协议/Internet 协议版本 6 (TCP/IPv6)统计数据

获取本机TCP连接信息

        private static void TCPlistener()
        {
            IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            IPEndPoint[] iPEndPoint = iPGlobalProperties.GetActiveTcpListeners();//
            Console.WriteLine("监听的IP地址个数为" + iPEndPoint.Length);
            Console.WriteLine("-------------------------------------------------");
            foreach (IPEndPoint iep in iPEndPoint)
            {
                Console.WriteLine("TCP监听的IP地址...........{0}", iep.Address);
                Console.WriteLine("TCP监听的IP地址端口.......{0}", iep.Port);
                Console.WriteLine("TCP监听的IP遵循的协议.....{0}", iep.AddressFamily);
                Console.WriteLine("-------------------------------------------------");

            }
        }
   private static void TCPtraffic()
        {
            IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
            Console.WriteLine($"主机名:{iPGlobalProperties.HostName} 主机所在的域{iPGlobalProperties.DomainName}");
            IPGlobalStatistics iPGlobalStatistics = iPGlobalProperties.GetIPv4GlobalStatistics();
            Console.WriteLine("IP数据包默认生存时间:" + iPGlobalStatistics.DefaultTtl);
            Console.WriteLine("网络接口的数量:" + iPGlobalStatistics.NumberOfInterfaces);
            Console.WriteLine("分配的IPv4地址的数目:" + iPGlobalStatistics.NumberOfIPAddresses);
            Console.WriteLine("路由数:" + iPGlobalStatistics.NumberOfRoutes);
            Console.WriteLine("出站数据波=包" + iPGlobalStatistics.OutputPacketRequests);
            Console.WriteLine("收到的数据包=" + iPGlobalStatistics.ReceivedPackets);
            Console.ReadLine();
        }

总结

要学会调试程序

通过断点调试解决问题。

学会查官方文档

官方写的很清楚

原文地址:https://www.cnblogs.com/delongzhang/p/12425766.html