C # programming _ card information detection and network traffic detection

Card information detection and network traffic detection


Each computer cable communications, to be by means of a hardware device, network card , referred to as NIC , NIC is Network Interface Controller an abbreviation. NIC is responsible for the bit stream into an electrical signal transmitted and the detected electrical signals into a bit stream and received.

network adapter:

  • Also known as computer network card is a hardware device connected to the network.

  • After the data sent to the network line, and data into packets of appropriate size on the computer is transmitted to organize the network.

    In C #, it provides System.Net.NetworkInformation namespace to provide information on the card.

These include:

  • Detection of the network card related information
  • This unit has a number of NIC, its name, speed, hardware address.
  • The machine detects network traffic
    • Network connection configuration, receiving the transmitted data packet and the like.

Card information detection related classes

Network Interface类

It provides network adapter configuration and statistics:

  • The number of network adapters

  • Network Adapter Model

  • Speed ​​network adapters

  • MAC address of the network adapter

  • Network adapter connection is available

Each network adapter comprising a NetworkInterface corresponding object.

Properties and methods Explanation
Name property Get the name of the network adapter
Speed ​​property Acquiring speed network adapter (* bit / * sec)
GetAllNetworkInterfaces 方法 Object Description Returns all the network adapters on the local computer
GetIPProperties method Description Returns the object of this network adapter configuration
Getisnetworkavalble 方法 It indicates whether there is any available network connection
GetPhysicalAddress method Returns the adapter Media Access Control (MAC) address
Supports method Indicates whether the interface supports the specified protocol (IPv4 or IPv6)

Access to information card

 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 类

  • The machine detects all network adapter supports various address

    • Dns server's IP address, gateway address, and multicast addresses.
  • IPInterfaceProperties class is abstract and can not be instantiated.

    • Examples thereof obtained by GetIPProperties NetworkInterface object ()

IPInterfaceProperties class properties and methods used

Properties and methods Explanation
AnycastAddresses property Get assigned to this interface to any IP broadcast address
DhcpServerAddresses property Address to get this interface Dynamic Host Configuration Protocol (DHCP) server
DnsAddresses property This interface address acquisition Domain Name System (DNS) server
DnsSuffix property Get associated with this interface, the Domain Name System (DNS) suffix
GatewayAddresses property Get this interface gateway address
MulticastAddresses property Obtaining a multicast address assigned to this interface
UnicastAddresses property Get unicast addresses assigned to this interface
GetIPv4Properties method Get this network interface Internet protocol version (IPv4) configuration data
GetIPv6Properties way Get this network interfaces of the Internet Protocol version (IPv6) configuration data

Examples card information unicast address

 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();

Get gateway address

 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();

Obtain any broadcast address

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

Address to get this interface Dynamic Host Configuration Protocol (DHCP) server

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

            }
        }

This interface address acquisition Domain Name System (DNS) server

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

Get this network interface Internet protocol version (IPv4) configuration data

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

Tips alignment of

 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'));
        }

to sum up

To learn debugger

By breakpoint debugging solve the problem.

Learn to check the official documentation

Official written very clearly

Released seven original articles · won praise 0 · Views 389

Guess you like

Origin blog.csdn.net/c1ata/article/details/104692920