C# 获取局域网IP和MAC地址

C#遍历局域网的几种方法及比较
扫描局域网IP列表的几种方法
很多软件都有获知局域网在线计算机IP的功能,但是在.net怎么实现呢,有好多方法,
下面我给大家介绍几种,供大家参考。
 
1、微软社区上介绍了使用Active Directory 来遍历局域网
利用DirectoryEntry组件来查看网络
网址: http://www.microsoft.com/china/communITy/program/originalarticles/techdoc/DirectoryEntry.mspx
private void EnumComputers()

{

    using(DirectoryEntry root = new DirectoryEntry("WinNT:"))

    {

      foreach(DirectoryEntry domain in root.Children)

      {

        Console.WriteLine("Domain | WorkGroup: "+domain.Name);

        foreach(DirectoryEntry computer in domain.Children)

    {

     Console.WriteLine("Computer: "+computer.Name);

    }

   }

}

}

效果评价:速度慢,效率低,还有一个无效结果 Computer: Schema 使用的过程中注意虑掉。
 
2、利用Dns.GetHostByAddress和IPHostEntry遍历局域网
private void EnumComputers()

{

for (int i = 1; i <= 255; i++)

{

string scanIP = "192.168.0." + i.ToString();

 

IPAddress myScanIP = IPAddress.Parse(scanIP);

 

IPHostEntry myScanHost = null;

 

try

{

    myScanHost = Dns.GetHostByAddress(myScanIP);

}

 

catch

{

    continue;

}

 

if (myScanHost != null)

{

    Console.WriteLine(scanIP+"|"+myScanHost.HostName);

}

} 

}

效果评价:效率低,速度慢,不是一般的慢。
3、使用System.Net.NetworkInformation.Ping来遍历局域网
private void EnumComputers()

{

try

{

   for (int i = 1; i <= 255; i++)

   {

     Ping myPing;

     myPing = new Ping();

     myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);

 

     string pingIP = "192.168.0." + i.ToString();

     myPing.SendAsync(pingIP, 1000, null);

   }

}

catch

{

}

}

 

PRIVATE void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)

{

if (e.Reply.Status == IPStatus.Success)

{

    Console.WriteLine(e.Reply.Address.ToString() + "|" + Dns.GetHostByAddress(IPAddress.Parse(e.Reply.Address.ToString())).HostName);

}

 

}

 
效果评价:速度快,效率高,如果只取在线的IP,不取计算机名,速度会更快。
需要注意的是取计算机名称如果用Dns.GetHostByAddress取计算机名称,结果虽然正确,但VS2005会提示该方法已过时,但仍能使用。
如果用它推荐的替代方法Dns.GetHostEntry,则有个别计算机的名称会因超时而获得不到。
 获取局域网内的IP和MAC地址代码如下:
using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

using System.Runtime.InteropServices;

using System.Net;

using System.Net.NetworkInformation;

 

namespace MacApp

{

 

    public partial class Form1 : Form

    {

        [DllImport("ws2_32.dll")]

        private static extern int inet_addr(string cp);

        [DllImport("IPHLPAPI.dll")]

        private static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 pMacAddr, ref Int32 PhyAddrLen);

        public Form1()

        {

            InitializeComponent();

        }

 



        private void button1_Click(object sender, EventArgs e)

        {

            richTextBox1.Text = GetMacAddress(textBox1.Text);//获取远程IP(不能跨网段)的MAC地址

        }

        private string GetMacAddress(string hostip)//获取远程IP(不能跨网段)的MAC地址

        {

            string Mac = "";

            try

            {

                Int32 ldest = inet_addr(hostip); //将IP地址从 点数格式转换成无符号长整型

                Int64 macinfo = new Int64();

                Int32 len = 6;

                SendARP(ldest, 0, ref macinfo, ref len);

                string TmpMac = Convert.ToString(macinfo, 16).PadLeft(12, '0');//转换成16进制  注意有些没有十二位

                Mac = TmpMac.Substring(0, 2).ToUpper();//

                for (int i = 2; i < TmpMac.Length; i = i + 2)

                {

                    Mac = TmpMac.Substring(i, 2).ToUpper() + "-" + Mac;

                }

            }

            catch (Exception Mye)

            {

                Mac = "获取远程主机的MAC错误:" + Mye.Message;

            }

            return Mac;

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            if (Dns.GetHostEntry(Dns.GetHostName()).AddressList.Length > 0)

            {

                textBox1.Text = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0].ToString();//获取本机IP地址

            }

        }

 

        private void button2_Click(object sender, EventArgs e)

        {

 

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < 2; i++)

            {

                EnumComputers(i);

            }

 

        }

 

        private void EnumComputers(int n)

        {

 

            try

            {

                for (int i = 1; i <= 255; i++)

                {

                    Ping myPing;

                    myPing = new Ping();

                    myPing.PingCompleted += new PingCompletedEventHandler(myPing_PingCompleted);

 

                    string pingIP = "192.168." + n.ToString() + "." + i.ToString();

                    myPing.SendAsync(pingIP, 1000, null);

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

 

        private void myPing_PingCompleted(object sender, PingCompletedEventArgs e)

        {

            StringBuilder sb = new StringBuilder();

 

            if (e.Reply.Status == IPStatus.Success)

            {

                sb.Append("IP:" + e.Reply.Address.ToString() + "\r\n");

                string mac = GetMacAddress(e.Reply.Address.ToString());

                sb.Append("MAC:" + mac + "\r\n");

 

            }

            this.textBox2.Text += sb.ToString();

        }

 

    }

}

 

你可能感兴趣的:(mac)