秋 叶
      程序书写人生,代码编织未来! 
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

获得局域网中IP和计算机名称

Posted on 2006-04-10 12:30  秋叶  阅读(711)  评论(0)    收藏  举报

本程序中采用多线程搜索方法.获得局域网网段为"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();
                  }
              }              
         }
  }

}