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

C#遍历局域网的几种方法及比较
2009-07-03 10:08

扫描局域网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();
        }

    }
}

 

 

C#的本机IP地址

IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
           
string myip = IpEntry.AddressList[0].ToString();

这样,如果没有安装IPV6协议,可以取得IP地址.  但是如果安装了IPV6,就取得的是IPV6的IP地址.

string myip = IpEntry.AddressList[1].ToString();
这样就在IPV6的情况下取得IPV4的IP地址.

但是,如果本机有很多块网卡, 如何得到IpEntry.AddressList[多少]才是本机的局网IPV4地址呢
?

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值