单线程IP地址解析
文章目录
目标程序
- 界面如下图
- 设计方法:完成单个IP地址解析,循环调用方法,完成扫描。
- 注意用stopwatch计算时间。
实现思路
- 先知道怎么解析一个单个的IP地址。
- 用循环的方法解析多个IP地址。
- 设计程序的界面
- 设计事件
实现过程
在控制台中尝试过程
//实现的思路
//扫描的地址是自己设定的,我们需要设置变量来保存它们。
//扫描的IP地址由两端组成,一个地址前缀,另外一部分时起始值和终止值
//我们需要输出的是IP地址,扫描时间,和dns主机名
//IP地址可以由IPAddress.Parse转换
//可以通过Dns.GetHostEntry来解析
//扫描时间可以用stopwatch来统计
//还需要判断IP地址是否合法
string addressPrefix = "127.0.0.";//用来存储地址前缀
int startingValue = 1;//存放起始值
int stopingValue = 2;//存放终止值
// if (startingValue <= stopingValue && startingValue > 0 && startingValue <= 255 && stopingValue > 0 && stopingValue <= 255)
//{不用if判断即可
//用循环来扫描多个IP地址
for (int i = startingValue; i <= stopingValue; i++)
{
string ipString = addressPrefix + i;
IPAddress ip;//不能直接定义在try里面,不然出了try就不能用了
IPHostEntry iPHostEntry;
string iphostname;
try//判断是否合法
{
// IPAddress ip = IPAddress.Parse(ipString);
ip = IPAddress.Parse(ipString);
//Dns解析
// IPHostEntry iPHostEntry = Dns.GetHostEntry(ip);
// string iphostname = iPHostEntry.HostName;//获取ip的主机名
// Console.WriteLine($"扫描地址:{ip},扫描用时,主机DNS名称:{iphostname}");
//不能大篇幅的try
//要精确点
}
catch (Exception ex)
{
Console.WriteLine("IP地址不合法");
break;
}
Stopwatch sw = new Stopwatch();//实例化一个秒表对象sw
sw.Start();//秒表开始
try
{ //Dns解析
iPHostEntry = Dns.GetHostEntry(ip);
iphostname = iPHostEntry.HostName;//获取ip的主机名
sw.Stop();//秒表结束
}
catch (Exception ex)
{
iphostname = "不在线";
}
long time = sw.ElapsedMilliseconds;//获取这段过程的时间
Console.WriteLine($"扫描地址:{ip},扫描用时:{time}毫秒,主机DNS名称:{iphostname}");
}
//string ipString = addressPrefix + startingValue;//拼接成IP地址字符串
Console.ReadLine();
}
/* else
{
Console.WriteLine("IP地址不合法");
Console.ReadLine();
}*//
设计WPF界面
<Window x:Class="WpfApp_SingleThreadIPScan.MainWindow"
xmlns="http://s