【C#】第1章_IP地址转换与域名解析_网卡信息检测与流量检测

这篇博客介绍了C#中进行IP地址转换、域名解析的方法,包括使用Dns类的GetHostAddresses和GetHostEntry等方法。同时,详细讲解了如何获取和展示网络接口信息,以及进行网络流量统计,利用NetworkInterface和IPGlobalProperties类获取本地计算机的网络适配器和通信统计数据。
摘要由CSDN通过智能技术生成

Content


链接:x:Name和Name的区别.

  • App.xaml
    添加静态资源 样式,LabelStyle,BorderStyle
    <Application.Resources>
        <Style x:Key="LabelStyle" TargetType="Label">
            <Setter Property="FontSize" Value="14"/>
            <Setter Property="HorizontalContentAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Background" Value="AliceBlue"/>
        </Style>
        <Style x:Key="BorderStyle" TargetType="Border">
            <Setter Property="Height" Value="35"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Background" Value="AliceBlue"/>
        </Style>
    </Application.Resources>
  • MainWindow.xaml
    设置 Grid 的列,具体不清楚,
    貌似给第一个 Rectangle 设了 2 列,后两个 Rectangle 在第一列,frame 在第二列;
    其中设置了 StackPanel 的资源,指定了 Button 的样式;
<Window x:Class="ch01.MainWindow"
		...
        Title="第一章示例" Height="500" Width="700"
        Background="#FFF0F9D8" WindowStartupLocation="CenterScreen">
        
    <Grid Margin="20">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Rectangle Grid.ColumnSpan="2" Fill="White"
                   RadiusX="14" RadiusY="14" Stroke="Red" StrokeDashArray="3"/>
        <Rectangle Grid.Column="0" Margin="7" Fill="#FFF0F9D8"
                   RadiusX="10" RadiusY="10" Stroke="Black" StrokeDashArray="3"/>
        <Rectangle Grid.Column="0" Margin="20" Fill="AliceBlue" Stroke="Blue"/>
        <ScrollViewer Grid.Column="0" Margin="22">
            <StackPanel>
                <StackPanel.Resources>
                    <Style TargetType="Button">
                        <Setter Property="HorizontalContentAlignment" Value="Center"/>
                        <Setter Property="Margin" Value="5 10 5 0"/>
                        <Setter Property="Padding" Value="15 0 15 0"/>
                        <Setter Property="FontSize" Value="10"/>
                        <EventSetter Event="Click" Handler="button_Click"/>
                    </Style>
                </StackPanel.Resources>
                <Button Content="例1" Tag="/Examples/DnsExamplePage.xaml"/>
                <Button Content="例2" Tag="/Examples/NetworkInterfacePage.xaml"/>
                <Button Content="例3" Tag="/Examples/IPGlobalStaticsPage.xaml"/>
            </StackPanel>
        </ScrollViewer>
        <Frame Name="frame1" Grid.Column="1" Margin="10" BorderThickness="1"
               BorderBrush="OrangeRed" NavigationUIVisibility="Hidden"/>
    </Grid>
</Window>

  • MainWindow.xaml.cs
    所用类:
    Frame
    new Uri(btn.Tag.ToString(), UriKind.Relative)

    详见注释;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ch01
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Button oldButton = new Button();    //new 一个 Button 待命
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button_Click(object sender, RoutedEventArgs e)
        {
            Button btn = e.Source as Button;
            btn.Foreground = Brushes.Red;           //当前 button 前景刷红
            oldButton.Foreground = Brushes.Black;   //以前的刷黑
            oldButton = btn;
            frame1.Source = new Uri(btn.Tag.ToString(), UriKind.Relative);
            //给 frame 资源一个 uri 相对地址 找到对应页
        }
    }
}

为了使各个标签更清楚,改了一下边框颜色,后面几张图没换;
在这里插入图片描述

  • DnsExamplePage.xaml
    Label 和 Border 标签引用了相应的静态资源;
<Page x:Class="ch01.Examples.DnsExamplePage"
      ...
      d:DesignHeight="450" d:DesignWidth="800"
      Title="DnsExamplePage">

    <DockPanel>
        <Label DockPanel.Dock="Top" Content="DNS域名解析和IP地址转换的基本用法"
               Style="{StaticResource LabelStyle}"/>
        <Border DockPanel.Dock="Bottom" Style="{StaticResource BorderStyle}">
            <Button Name="btn" HorizontalAlignment="Center"
                    Padding="10 0 10 0" Content="运行" Click="btn_Click"/>
        </Border>
        <ScrollViewer>
            <StackPanel Background="White" TextBlock.LineHeight="20">
                <TextBlock x:Name="textBlock1" Margin="0 10 0 0" TextWrapping="Wrap"/>
            </StackPanel>
        </ScrollViewer>
    </DockPanel>
</Page>

  • Examples\DnsExamplePage.xaml.cs
    DNS域名解析和IP地址转换的基本用法;
    所用类及方法:
    Dns.GetHostAddresses(“www.cctv.com”);
    Dns.GetHostName();
    Dns.GetHostEntry(hostName);
    IPAddress.Parse("::1");
    new IPEndPoint(localip, 80);

    详见注释;
using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Net;
using System.Net.Sockets;

namespace ch01.Examples
{
    /// <summary>
    /// DnsExamplePage.xaml 的交互逻辑
    /// </summary>
    public partial class DnsExamplePage : Page
    {
        public DnsExamplePage()
        {
            InitializeComponent();
        }
        private void btn_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("获取www.cctv.com的所有IP地址: ");
            try
            {
                IPAddress[] ips = Dns.GetHostAddresses("www.cctv.com");	//获取 IP 地址组
                foreach(IPAddress ip in ips)
                {
                    sb.AppendLine(ip.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "获取失败");
            }

            string hostName = Dns.GetHostName();	//获取本机 主机名
            sb.AppendLine("获取本机所有IP地址: ");
            IPHostEntry me = Dns.GetHostEntry(hostName);	//获取本机 IP 地址组
            foreach (IPAddress ip in me.AddressList)
            {
                if(ip.AddressFamily == AddressFamily.InterNetwork)
                {	//判断 IP 地址族是 IPv4 还是 IPv6
                    sb.AppendLine("IPv4: " + ip.ToString());
                }
                else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    sb.AppendLine("IPv6: " + ip.ToString());
                }
                else
                {
                    sb.AppendLine("其他: " + ip.ToString());
                }
            }

            IPAddress localip = IPAddress.Parse("::1"); //IPv6 回路测试地址 Parse 方法转换字符串
            Output(sb, localip);
            IPAddress localip1 = IPAddress.Parse("127.0.0.1");  //IPv4 回路测试地址
            Output(sb, localip1);
            textBlock1.Text = sb.ToString();
            
        }

        private static void Output(StringBuilder sb, IPAddress localip)
        {
            IPEndPoint iep = new IPEndPoint(localip, 80);	//包含 IP 地址和端口号
            if(localip.AddressFamily == AddressFamily.InterNetworkV6)
            {
                sb.Append("IPv6端点: " + iep.ToString());
            }
            else
            {
                sb.Append("IPv6端点: " + iep.ToString());
            }
            sb.Append(", 端口 " + iep.Port);
            sb.Append(", 地址 " + iep.Address);
            sb.AppendLine(", 地址族 " + iep.AddressFamily);
        }
    }
}

在这里插入图片描述

  • NetworkInterfacePage.xaml
    这三个页的 xaml 代码是相似的;
<Page x:Class="ch01.Examples.NetworkInterfacePage"
      ...
      d:DesignHeight="450" d:DesignWidth="800"
      Title="NetworkInterfacePage">

    <DockPanel>
        <Label DockPanel.Dock="Top" Content="获取网络适配器信息"
               Style="{StaticResource LabelStyle}"/>
        <Border DockPanel.Dock="Bottom" Style="{StaticResource BorderStyle}">
            <Button Name="btn" HorizontalAlignment="Center"
                    Padding="10 0 10 0" Content="运行" Click="btn_Click"/>
        </Border>
        <ScrollViewer>
            <StackPanel Background="White" TextBlock.LineHeight="20">
                <TextBlock x:Name="textBlock1" Margin="0 10 0 0" TextWrapping="Wrap"/>
            </StackPanel>
        </ScrollViewer>
    </DockPanel>
</Page>

  • Examples\NetworkInterfacePage.xaml.cs
    获取网络适配器信息;
    NetworkInterface.GetAllNetworkInterfaces();
    adapter.GetPhysicalAddress().GetAddressBytes();
    adapter.GetIPProperties();

    详见注释;
using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Net;
using System.Net.NetworkInformation;

namespace ch01.Examples
{
    /// <summary>
    /// NetworkInterfacePage.xaml 的交互逻辑
    /// </summary>
    public partial class NetworkInterfacePage : Page
    {
        public NetworkInterfacePage()
        {
            InitializeComponent();
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            //获取描述本机的 所有网络适配器对象 是个静态工厂方法,因为能创建新的对象
            sb.AppendLine("适配器个数: " + adapters.Length);
            int index = 0;
            foreach (NetworkInterface adapter in adapters)
            {
                index++;
                //显示网络适配器描述信息、名称、类型、速度、MAC地址
                sb.AppendLine("---第" + index + "个适配器信息---");
                sb.AppendLine("描述信息: " + adapter.Description);
                sb.AppendLine("名称: " + adapter.Name);
                sb.AppendLine("类型: " + adapter.NetworkInterfaceType);
                sb.AppendLine("速度: " + adapter.Speed / 1000 / 1000 + "M");
                byte[] macBytes = adapter.GetPhysicalAddress().GetAddressBytes();	
                //需要用字节数组存 MAC 地址
                sb.AppendLine("MAC地址: " + BitConverter.ToString(macBytes));
                //获取 IPInterfaceProperties 实例 //静态工厂方法
                IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
                //获取并显示 DNS 服务器 IP 地址信息
                IPAddressCollection dnsServers = adapterProperties.DnsAddresses;
                //也是一组 IP 地址
                if(dnsServers.Count > 0)
                {
                    foreach(IPAddress dns in dnsServers)
                    {
                        sb.AppendLine("DNS服务器IP地址: " + dns);
                    }
                }
            }
            textBlock1.Text = sb.ToString();
        }
    }
}

在这里插入图片描述

  • IPGlobalStaticsPage.xaml
<Page x:Class="ch01.Examples.IPGlobalStaticsPage"
      ...
      d:DesignHeight="450" d:DesignWidth="800"
      Title="IPGlobalStaticsPage">

    <DockPanel>
        <Label DockPanel.Dock="Top" Content="网络流量统计"
               Style="{StaticResource LabelStyle}"/>
        <Border DockPanel.Dock="Bottom" Style="{StaticResource BorderStyle}">
            <Button Name="btn" HorizontalAlignment="Center"
                    Padding="10 0 10 0" Content="运行" Click="btn_Click"/>
        </Border>
        <ScrollViewer>
            <StackPanel Background="White" TextBlock.LineHeight="20">
                <TextBlock x:Name="textBlock1" Margin="0 10 0 0" TextWrapping="Wrap"/>
            </StackPanel>
        </ScrollViewer>
    </DockPanel>
</Page>

  • Examples\IPGlobalStaticsPage.xaml.cs
    网络流量统计;
    IPGlobalProperties.GetIPGlobalProperties();
    properties.GetIPv4GlobalStatistics();

    IPGlobalProperties 类,提供了本地计算机网络连接和通信统计数据的信息;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Net.NetworkInformation;

namespace ch01.Examples
{
    /// <summary>
    /// IPGlobalStaticsPage.xaml 的交互逻辑
    /// </summary>
    public partial class IPGlobalStaticsPage : Page
    {
        public IPGlobalStaticsPage()
        {
            InitializeComponent();
        }

        private void btn_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
            IPGlobalStatistics ipstat = properties.GetIPv4GlobalStatistics();
            sb.AppendLine("本机注册域名: " + properties.DomainName);
            sb.AppendLine("接收数据包数: " + ipstat.ReceivedPackets);
            sb.AppendLine("转发数据报数: " + ipstat.ReceivedPacketsForwarded);
            sb.AppendLine("传送数据报数: " + ipstat.ReceivedPacketsDelivered);
            sb.AppendLine("丢弃数据报数: " + ipstat.ReceivedPacketsDiscarded);
            textBlock1.Text = sb.ToString();
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值