实验2:IP地址转换和域名解析练习
1.通过本实验,复习本教材各章例子里的前端主界面和子页面的实现。
2、通过本实验,熟悉和掌握IPAddress类、IPEndPoint类、IPHostEntry类、DNS类的使用。
1、创建一个WPF应用程序项目
2、将App.xaml中的Application.Resources节内容改为
3、修改MainWindow.xaml及代码隐藏类
MainWindow.xaml
MainWindow.xaml.cs主要内容
4、用鼠标右键单击项目,选择【添加】-【新建文件夹】命令,在项目中添加一个名为Examples的文件夹。
5、用鼠标右键单击Examples文件夹,选择【添加】-【页】命令,在该文件夹下添加一个名为Page1.xaml的页。之后再按同样方法添加页Page2.xaml和Page3.xaml。
6、修改Page1.xaml的核心代码
Page1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
namespace 实验1_WPF练习.Examples
{
/// <summary>
/// Page1.xaml 的交互逻辑
/// </summary>
public partial class Page1 : Page
{
public Page1()
{
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");
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);
foreach (IPAddress ip in me.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{ 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回路测试地址
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);
if (localip.AddressFamily == AddressFamily.InterNetworkV6)
{ sb.Append("IPv6端点: " + iep.ToString()); }
else { sb.Append("IPv4端点: " + iep.ToString()); }
sb.Append(",端口 " + iep.Port);
sb.Append(",地址 " + iep.Address);
sb.AppendLine(",地址族 " + iep.AddressFamily);
}
}
}