使用C#扫描局域网

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.Net.NetworkInformation;

namespace P2PChat
{
    public partial class ListForm : Form
    {
        public ListForm()
        {
            InitializeComponent();
        }

        private void ListForm_Load(object sender, EventArgs e)
        {
            //获取本地机器名
           string _myHostName = Dns.GetHostName();
            //获取本机IP
           string _myHostIP = Dns.GetHostEntry(_myHostName).AddressList[0].ToString();

           //截取IP网段
           string ipDuan = _myHostIP.Remove(_myHostIP.LastIndexOf('.'));

           //枚举网段计算机
           for (int i = 1; i <= 255; i++)
           {
               Ping myPing = new Ping();
               myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
               string pingIP = ipDuan + "." + i.ToString();
               myPing.SendAsync(pingIP, 1000, null);
           }
        }

        //向ListBox添加扫描出的计算里信息
        void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
        {
            if (e.Reply.Status == IPStatus.Success)
            {
                listBox1.Items.Add(e.Reply.Address.ToString());
            }
        }

    }
}

posted on 2009-09-04 15:46  韩显川  阅读(706)  评论(0编辑  收藏  举报

导航