创建一个WPF应用程序,用多任务来扫描一个网段内的计算机,根据计算机的IP地址获取其主机名,程序运行结果如下:
废话不多说,直接上代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
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;
namespace A._2
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
int n = 0;
DateTime taskBegin = DateTime.Now;
public MainWindow()
{
InitializeComponent();
textBox_first.Text = "192.168.1.";
textBox_start.Text = "102";
textBox_end.Text = "105";
}
private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
IPAddress ipstart;
IPAddress ipend;
if (IPAddress.TryParse(textBox_first.Text + textBox_start.Text, out ipstart)&& IPAddress.TryParse(textBox_first.Text + textBox_end.Text, out ipend))
{
errorLable.Visibility = Visibility.Hidden;
}
else
{
errorLable.Visibility = Visibility.Visible;
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
IPAddress ipstart;
IPAddress ipend;
listBox.Items.Clear();
n = int.Parse(textBox_end.Text) - int.Parse(textBox_start.Text) + 1;
if (IPAddress.TryParse(textBox_first.Text + textBox_start.Text, out ipstart) && IPAddress.TryParse(textBox_first.Text + textBox_end.Text, out ipend))
{
errorLable.Visibility = Visibility.Hidden;
for (int i= int.Parse(textBox_start.Text); i<=int.Parse(textBox_end.Text);i++){
IPAddress ip = IPAddress.Parse(textBox_first.Text+i.ToString());
Thread t = new Thread(scan);
t.Start(ip);
}
}
else
{
errorLable.Visibility = Visibility.Visible;
}
}
private void scan(Object ip)
{
DateTime begin = DateTime.Now;
IPAddress ipAddress = (IPAddress)ip;
string hostName;
try
{
hostName = Dns.GetHostEntry(ipAddress).HostName;
}
catch
{
hostName = "(不在线)";
}
DateTime end = DateTime.Now;
TimeSpan ts = end - begin;
listBox.Dispatcher.Invoke(() => listBox.Items.Add("扫描地址:"+ ipAddress.ToString()+" 扫描用时:"+ ts.TotalMilliseconds+ "毫秒 " + " 主机名称:" +hostName));
n--;
if (n == 0) {
DateTime taskEnd = DateTime.Now;
TimeSpan taskAll = taskEnd - taskBegin;
MessageBox.Show("扫描完毕!总用时:"+ taskAll.TotalMilliseconds + "毫秒");
}
}
}
}
此程序还可以细致化一下,比如,起始值不能大于终止值,地址前缀后面的点,程序可以自动补全,错误提示细致化等等。