在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C#获取局域网内所有计算机的IP地址和MAC地址

C#获取局域网内所有计算机的IP地址和MAC地址

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.06M
  • 下载次数:84
  • 浏览次数:767
  • 发布时间:2019-07-07
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.rar
  • 所需积分:2
 相关标签: 局域网 计算机 MAC 地址 计算

实例介绍

【实例简介】C#实现获取局域网内所有计算机的IP地址和MAC地址的控制台应用程序源码 程序启动时首先获取本机的IP和MAC地址; 然后获取局域网内所有计算机的IP地址; 输入IP地址回车,获取该IP的MAC地址; 输入“STARTSCAN”回车,重新获取局域网内所有计算机的IP地址; 输入“ALLSCAN”回车,获取网段内所有IP(0-255)的MAC地址 代码见压缩包

【实例截图】

from clipboard

【核心代码】

using System;
using System.Collections.Generic;
using System.Text;

using System.Runtime.InteropServices;
using System.Net;
using System.Management;

using System.Collections;
using System.DirectoryServices;

using System.Text.RegularExpressions;
using System.Diagnostics;

using System.IO;

using System.Threading;

namespace GetIPMAC
{
    class Program
    {
        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);

        static void Main(string[] args)
        {
            Program pro = new Program();
            Console.WriteLine("获取本机和目标机的MAC地址----LC编辑");
            Console.WriteLine();
            Console.WriteLine("本机网卡信息:");
            string localIP = pro.GetLocalIP()[0];
            Console.WriteLine("本机IP:"   localIP   " \n本机MAC: "   pro.getLocalMac());
            Console.WriteLine();

            #region 获取主机名称--保存到文档--转换成地址
            ////获取所有机器的机器名,并存于c:\\xyq.txt
            //System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(); 
            //psi.FileName = @"C:\WINDOWS\system32\cmd.exe";
            //psi.Arguments = @"/c net view > c:\\xyq.txt";//需要加上/c这个参数   
            //psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            //System.Diagnostics.Process.Start(psi);
            
            ////读取c:\\xyq.txt文本文件里所有含有”\\”前缀的记录进arrText
            //StreamReader objReader = new StreamReader("c:\\xyq.txt");
            //string sLine = "";
            //ArrayList arrText = new ArrayList();
            //ArrayList arrip = new ArrayList();
            //while (sLine != null)
            //{
            //    sLine = objReader.ReadLine();
            //    if (sLine != null)
            //    {
            //        if (sLine.IndexOf("\\") == 0)//这句的功能是读取文本文件里所有含有”\\”前缀的记录   
            //        {
            //            arrText.Add(sLine);
            //        }
            //    }
            //}
            //objReader.Close();

            ////把机器的主机名转换成ip地址
            //foreach (string str_out in arrText)//遍历这个数组
            //{
            //    string hostname = str_out.Substring(2, str_out.IndexOf(" ") - 2);
            //    try
            //    {
            //        System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostname);
            //        for (int j = 0; j < addressList.Length; j  )
            //        {
            //            arrip.Add(addressList[j].ToString());
            //            Console.WriteLine(hostname   "  :  "   addressList[j].ToString());
            //        }
            //    }
            //    catch(Exception ex)
            //    {
            //        Console.WriteLine(hostname   "  :  "   ex.Message);
            //    }
            //}
            //File.Delete("c:\\xyq.txt");
            #endregion

            Console.WriteLine();
            Console.WriteLine("正在获取网络主机列表......");
            pro.GetOnlineComputerList();
            Console.WriteLine("获取完毕!");
            #region 其他获取主机列表方法
            //pro.StartScan();
            //Thread.Sleep(1000 * 60);
            //ArrayList allUsers = ComputerAddressInfo.computerList;//pro.GetComputerList();
            //if (allUsers.Count > 0)
            //{
            //    for (int i = 0; i < allUsers.Count; i  )
            //    {
            //        string[] strPCInf = (string[])allUsers[i];
            //        Console.WriteLine(strPCInf[0].ToString()   "  :  "   strPCInf[1].ToString());
            //    }
            //}
            //else
            //    Console.WriteLine("没有找到主机!");
            #endregion

            Console.WriteLine();
            Console.WriteLine("请输入目标机IP地址:");
            string remoteIP = Console.ReadLine();
            while (remoteIP.ToUpper() != "EXIT")
            {
                if (remoteIP.ToUpper() == "STARTSCAN")
                {
                    Console.WriteLine("重新获取网络主机列表......");
                    pro.GetOnlineComputerList();
                    Console.WriteLine("获取完毕!");
                }
                else if (remoteIP.ToUpper() == "ALLSCAN")
                {
                    Console.WriteLine("获取网络所有IP的主机列表......");
                    pro.GetAllIPComputerList(localIP);
                    Console.WriteLine("所有IP获取完毕!");
                }
                else
                {
                    if (remoteIP.Contains(":"))
                    {
                        if (remoteIP.Substring(0, remoteIP.IndexOf(":")).ToUpper() == "PC")
                        {
                            string pcName = remoteIP.Substring(remoteIP.IndexOf(":")   1);
                            try
                            {
                                string[] temp = pro.getRemoteIP(pcName);//目标机名
                                for (int i = 0; i < temp.Length; i  )
                                {
                                    Console.WriteLine(pcName   "的IP为:"   temp[i]);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(pcName   ":"   ex.Message);
                            }
                        }
                    }
                    else
                    {
                        //string remoteMac = pro.getRemoteMac(getLocalIP(), remoteIP);//本机IP和目标机IP
                        string remoteMac = pro.GetRemoteMac(remoteIP);
                        Console.WriteLine("目标机IP:"   remoteIP   " \n目标机MAC: "   remoteMac);
                        Console.WriteLine("====================================");
                    }
                }
                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("请输入目标机IP地址:");
                remoteIP = Console.ReadLine();
            }
        }

        //获取本机的IP,返回地址列表第一个   
        public string getLocalIP()
        {
            string strHostName = Dns.GetHostName(); //得到本机的主机名   
            IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP   
            string strAddr = ipEntry.AddressList[0].ToString();
            return strAddr;
        }

        //获取本机IP,返回地址列表数组
        public string[] GetLocalIP() 
        {
            string hostName = Dns.GetHostName(); 
            IPHostEntry ipEntry=Dns.GetHostByName(hostName); 
            IPAddress[] arr=ipEntry.AddressList; 
            string[] result = new string[arr.Length];
            for (int i = 0; i < arr.Length; i  )
            {
                result[i] = arr[i].ToString();
            }
            return result; 
        }

        //获取本机的MAC   
        public string getLocalMac()
        {
            string mac = null;
            ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection queryCollection = query.Get();
            foreach (ManagementObject mo in queryCollection)
            {
                if (mo["IPEnabled"].ToString() == "True")
                    mac = mo["MacAddress"].ToString();
            }
            return mac.ToUpper();
        }

        //获得本机的MAC地址 
        public string GetLocalMac()
        {
            string strMac = string.Empty; 
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 
            ManagementObjectCollection moc = mc.GetInstances(); 
            foreach(ManagementObject mo in moc) 
            { 
                if ((bool)mo["IPEnabled"] == true) 
                    strMac  = mo["MacAddress"].ToString(); 
            } 
            return strMac.ToUpper(); 
        } 

        //获取远程主机IP   
        public string[] getRemoteIP(string RemoteHostName)
        {
            IPHostEntry ipEntry = Dns.GetHostByName(RemoteHostName);
            IPAddress[] IpAddr = ipEntry.AddressList;
            string[] strAddr = new string[IpAddr.Length];
            for (int i = 0; i < IpAddr.Length; i  )
            {
                strAddr[i] = IpAddr[i].ToString();
            }
            return strAddr;
        }

        //获取远程主机MAC方法一:使用API,利用ARP协议,只能获得同网段计算机的MAC
        public string getRemoteMac(string localIP, string remoteIP)
        {
            Int32 ldest = inet_addr(remoteIP); //目的ip    
            Int32 lhost = inet_addr(localIP); //本地ip    

            try
            {
                Int64 macinfo = new Int64();
                Int32 len = 6;
                int res = SendARP(ldest, 0, ref macinfo, ref len);
                string remote = Convert.ToString(macinfo, 16);
                if (remote == "0")
                    return remote;
                if (remote.Length < 12)
                {
                    remote = remote.PadLeft(12, '0');
                }
                StringBuilder remoteMac = new StringBuilder();
                for (int i = remote.Length - 2; i >= 0; i = i - 2)
                {
                    remoteMac.Append(remote.Substring(i, 2));
                    remoteMac.Append(":");
                }
                if (remoteMac.Length > 1)
                {
                    remoteMac.Remove(remoteMac.Length - 1, 1);
                }
                return remoteMac.ToString().ToUpper();
            }
            catch (Exception err)
            {
                Console.WriteLine("Error:{0}", err.Message);
                return err.Message;
            }
        }

        //获取远程主机MAC方法二:使用API,利用ARP协议,只能获得同网段计算机的MAC 
        //[DllImport("Iphlpapi.dll")]
        //private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        //[DllImport("Ws2_32.dll")]
        //private static extern Int32 inet_addr(string ip); 
        public string GetRemoteMac(string clientIP)
        {
            string ip = clientIP;
            if (ip == "127.0.0.1")
                ip = GetLocalIP()[0];
            Int32 ldest = inet_addr(ip);
            Int64 macinfo = new Int64();
            Int32 len = 6;
            try
            {
                SendARP(ldest, 0, ref macinfo, ref len);
                string originalMACAddress = Convert.ToString(macinfo, 16);
                if (originalMACAddress == "0")
                    return originalMACAddress;
                if (originalMACAddress.Length < 12)
                {
                    originalMACAddress = originalMACAddress.PadLeft(12, '0');
                }
                string macAddress = "";
                if (originalMACAddress.Length == 12)
                {
                    string mac1, mac2, mac3, mac4, mac5, mac6;
                    mac1 = originalMACAddress.Substring(10, 2);
                    mac2 = originalMACAddress.Substring(8, 2);
                    mac3 = originalMACAddress.Substring(6, 2);
                    mac4 = originalMACAddress.Substring(4, 2);
                    mac5 = originalMACAddress.Substring(2, 2);
                    mac6 = originalMACAddress.Substring(0, 2);
                    macAddress = mac1   "-"   mac2   "-"   mac3   "-"   mac4   "-"   mac5   "-"   mac6;
                }
                return macAddress.ToUpper();
            }
            catch (Exception err)
            {
                Console.WriteLine("Error:{0}", err.Message);
                return err.Message;
            }
        }

        //获取远程主机MAC方法三:使用windows的命令nbtstat,使用此方法需要足够的操作系统的权限。在Web中,可以将ASP.net用户加入管理员组。
        public string GetRemoteMacByNetBIOS(string clientIP) 
        { 
            string ip = clientIP; 
            if ( ip == "127.0.0.1")
                ip = GetLocalIP()[0]; 
            string dirResults=""; 
            ProcessStartInfo psi  = new ProcessStartInfo(); 
            Process proc = new Process(); 
            psi.FileName = "nbtstat.exe"; 
            //psi.RedirectStandardInput = false; 
            psi.RedirectStandardOutput = true;psi.RedirectStandardError=true; 
            psi.Arguments = "-A "   ip; 
            psi.UseShellExecute = false; 
            proc = Process.Start(psi); 
            dirResults = proc.StandardOutput.ReadToEnd(); 
            string error = proc.StandardError.ReadToEnd(); 
            proc.WaitForExit(); 
            dirResults=dirResults.Replace("\r","").Replace("\n","").Replace("\t",""); 
            Regex reg=new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC",RegexOptions.IgnoreCase|RegexOptions.Compiled); 
            Match mc=reg.Match(dirResults "__MAC"); 
            if(mc.Success) 
            { 
                return mc.Groups["key"].Value.ToUpper(); 
            } 
            else 
            {
               return ""; 
            } 
        }

        //获取所有计算机列表方法一:使用Active Directory
        public ArrayList GetComputerList()
        {
            ArrayList list = new ArrayList();
            DirectoryEntry root = new DirectoryEntry("WinNT:");
            DirectoryEntries domains = root.Children;
            domains.SchemaFilter.Add("domain");
            foreach (DirectoryEntry domain in domains)
            {
                DirectoryEntries computers = domain.Children;
                computers.SchemaFilter.Add("computer");
                foreach (DirectoryEntry computer in computers)
                {
                    object[] arr = new string[2];
                    IPHostEntry iphe = null;
                    try
                    {
                        iphe = Dns.GetHostByName(computer.Name);

                        //arr[0] = domain.Name;
                        arr[0] = computer.Name;
                        if (iphe != null)
                        {
                            arr[1]  = iphe.AddressList[0].ToString();
                        }
                    }
                    catch(Exception ex)
                    {
                        arr[0] = computer.Name;
                        arr[1] = ex.Message.ToString();
                    }
                    list.Add(arr);
                }
            }
            return list;
        }

        //获取所有计算机列表方法二:利用多线程来对每个IP逐个扫描的方式,此方法速度比较慢
        public void StartScan()
        {
            ComputerAddressInfo cai = new ComputerAddressInfo("192.168.1", 9, 10);
            Thread thScan = new Thread(new ThreadStart(cai.ScanComputers));
            thScan.Start();
        }

        public void GetOnlineComputerList()
        {
            DirectoryEntry root = new DirectoryEntry("WinNT:");
            DirectoryEntries domains = root.Children;
            domains.SchemaFilter.Add("domain");
            foreach (DirectoryEntry domain in domains)
            {
                DirectoryEntries computers = domain.Children;
                computers.SchemaFilter.Add("computer");
                foreach (DirectoryEntry computer in computers)
                {
                    string[] arr = new string[3];
                    IPHostEntry iphe = null;
                    try
                    {
                        iphe = Dns.GetHostByName(computer.Name);

                        arr[0] = domain.Name;
                        arr[1] = computer.Name;
                        if (iphe != null)
                        {
                            arr[2]  = iphe.AddressList[0].ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        arr[0] = domain.Name;
                        arr[1] = computer.Name;
                        arr[2] = ex.Message.ToString();
                    }
                    Console.WriteLine(arr[1].ToString()   "  :  "   arr[2].ToString());
                }
            }
        }

        public void GetAllIPComputerList(string localip)
        {
            string strnet = localip.Substring(0, localip.LastIndexOf(".")   1);
            for (int i = 1; i < 255; i  )
            {
                string remoteip = strnet   i;
                string remotemac = GetRemoteMac(remoteip);
                Console.WriteLine(remoteip   "  :  "   remotemac);
            }
        }
    }
}

实例下载地址

C#获取局域网内所有计算机的IP地址和MAC地址

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警