• 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地址呢?

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/mane_yao/archive/2010/05/12/5583075.aspx

  • 相关阅读:
    常用坐标系椭球参数整理
    ArcEngine编辑保存错误:Unable to create logfile system tables
    ArcEngine:The XY domain on the spatial reference is not set or invalid错误
    dockManager中DockPanel的刷新问题!
    ibatis实现Iterate的使用
    mongodb用子文档做为查询条件的两种方法
    Eclipse中的文件导航插件StartExplorer
    mongoVUE的增删改查操作使用说明
    什么是脏读,不可重复读,幻读
    转:Maven常用命令
  • 原文地址:https://www.cnblogs.com/mane/p/1830033.html
Copyright © 2020-2023  润新知