代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Rows.Clear();
this.toolStripProgressBar1.Value = 0;
this.toolStripStatusLabel1.Text = "0%";
IPAddress address;
if(IPAddress.TryParse(textBox1.Text,out address))
{
Properties.Settings.Default.DefaultIP = textBox1.Text;
Properties.Settings.Default.Save();
Thread thd = new Thread
(() =>
Find(address.ToString()));
thd.IsBackground = true;
thd.Start();
}
else
{
MessageBox.Show("请输入默认网关正确格式:___.___.___.___");
}
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = Properties.Settings.Default.DefaultIP;
textBox1.AutoSize = false;
textBox1.TextAlign = HorizontalAlignment.Center;
toolStripProgressBar1.Value = 0;
toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
toolStripProgressBar1.Maximum = 255;
toolStripProgressBar1.Minimum = 0;
toolStripProgressBar1.MarqueeAnimationSpeed = 100;
toolStripProgressBar1.Step = 1;
toolStripStatusLabel1.Text = "0%";
}
private void Find(string address)
{
string[] n = address.Split('.');
string baseIP = n[0] + "." + n[1] + "." + n[2] + ".";
for (int i = 0; i <= 255; i++)
{
Ping ping;
ping = new Ping();
string pingIP = baseIP + i.ToString();
PingReply reply = ping.Send(pingIP, 10);
if (reply.Status == IPStatus.Success)
{
Action<string, string> addDelegate = (name, ip) => dataGridView1.Rows.Add(name, ip);
if (dataGridView1.InvokeRequired)
{
string ip = reply.Address.ToString();
string name = Dns.GetHostByAddress(IPAddress.Parse(reply.Address.ToString())).HostName;
dataGridView1.Invoke(addDelegate, name, ip);
}
}
this.Invoke(new Action(
() =>
{
toolStripProgressBar1.PerformStep();
toolStripStatusLabel1.Text = Math.Round((i + 1) * 100.0 / 256, 2).ToString() + "%";
}));
}
}
}