本程式中採用多線程搜尋方法.獲得區域網路網段為"192.168.0.1"中已開機的IP和電腦名稱,並分別顯示在tB1和tB2兩個文字框中.具體的方法如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Threading;
namespace LanHostSerach
{
public partial class Form1 : Form
{
private Thread[] thread;
private string str = "192.168.0";
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 線程搜尋
/// </summary>
private void SearchLink()
{
int i = Convert.ToUInt16(Thread.CurrentThread.Name);
IPAddress ScanIP = IPAddress.Parse(str + '.' + i.ToString()); //獲得掃描IP地址
IPHostEntry ScanHost = null;
try
{
ScanHost = Dns.GetHostByAddress(ScanIP); //獲得掃描IP地址主機資訊
}
catch (Exception E)
{
}
if (ScanHost != null)
{
tB1.Text = tB1.Text + ScanHost.HostName + ":" + ScanIP.ToString() + "\r\n";
tB2.Text = tB2.Text + ScanHost.HostName + "\r\n";
}
}
private void button1_Click(object sender, EventArgs e)
{
thread = new Thread[255];
ThreadStart threadMethod;
for (int i = 0; i < 255; i++) //建立255個線程掃描IP
{
threadMethod = new ThreadStart(SearchLink);
thread[i] = new Thread(threadMethod);
thread[i].Name = i.ToString();
thread[i].Start();
if (!thread[i].Join(100))
{
thread[i].Abort();
}
}
}
}
}