获得MAC地址的四个方法

来源:互联网 发布:linux ab压力测试工具 编辑:程序博客网 时间:2024/05/19 00:51
 
1.使用WMI。查询表Win32_NetworkAdapterConfiguration即可获得。

2.使用ARP协议。请看这里。
http://www.cnblogs.com/jiezhi/articles/87412.html

3.使用Windows命令nbtstat,也就是通过NetBIOS。请看这里。
http://www.cnblogs.com/jiezhi/articles/87412.html

4.查询SNMP(就是一种用于监视网络设备的协议)的MIB(管理信息数据库)。但这不是一件简单的事情,需要自己创建SNMP包,发送到交换机,然后对返回的响应进行解析。

下面是代碼:
复制  保存
using System;using System.Diagnostics;using System.Management;using System.Net;using System.Runtime.InteropServices;using System.Text.RegularExpressions;namespace MACAddress{    /// <summary>    /// MainClass 的摘要描述。    /// </summary>    internal class MainClass    {        /// <summary>        /// 應用程式的主進入點。        /// </summary>        [STAThread]        private static void Main(string[] args)        {            GetMACByWMI();            IPAddress[] ips = GetLocalIP();            foreach (IPAddress ip in ips)            {                Console.WriteLine(GetMacByARP(ip.ToString()));                string mac = GetRemoteMacByNetBIOS(ip.ToString());                if (mac.Length != 0)                    Console.WriteLine(mac);                else                    Console.WriteLine("Fail to get MACAddress by NetBIOS");                GetMACBySNMP(ip.ToString(), "yourGroupName@yourVlanNumber");            }            Console.ReadLine();        }        #region By WMI        public static void GetMACByWMI()        {            string query = "select MACAddress from Win32_NetworkAdapterConfiguration where IPEnabled='TRUE'";            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);            ManagementObjectCollection collection = searcher.Get();            foreach (ManagementObject mo in collection)            {                string mac = mo["MACAddress"].ToString();                Console.WriteLine(" Network card MAC Address is :{0}", mac);            }        }        #endregion        #region By ARP        [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 static string GetMacByARP(string clientIP)        {            string ip = clientIP;            Int32 ldest = inet_addr(ip);            Int64 macinfo = new Int64();            Int32 len = 6;            try            {                SendARP(ldest, 0, ref macinfo, ref len);            }            catch            {                return "";            }            string originalMACAddress = Convert.ToString(macinfo, 16);            if (originalMACAddress.Length < 12)            {                originalMACAddress = originalMACAddress.PadLeft(12, '0');            }            string macAddress;            if (originalMACAddress != "0000" && 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;            }            else            {                macAddress = "";            }            return macAddress.ToUpper();        }        public static IPAddress[] GetLocalIP()        {            string hostName = Dns.GetHostName();            IPHostEntry ipEntry = Dns.GetHostByName(hostName);            return ipEntry.AddressList;        }        #endregion        #region By NetBIOS        public static string GetRemoteMacByNetBIOS(string clientIP)        {            string ip = clientIP;            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 "";            }        }        #endregion        #region By SNMP        public static void GetMACBySNMP(string ip, string vlan)        {            int commLength, mibLength, dataStart, dataLength;            string nextMib, value;            SNMP conn = new SNMP();            string mib = "1.3.6.1.2.1.17.4.3.1.1";            int orgMibLength = mib.Length;            byte[] response = new byte[1024];            nextMib = mib;            while (true)            {                response = conn.Get("getnext", ip, vlan, nextMib);                commLength = Convert.ToInt16(response[6]);                mibLength = Convert.ToInt16(response[23 + commLength]);                dataLength = Convert.ToInt16(response[25 + commLength + mibLength]);                dataStart = 26 + commLength + mibLength;                value = BitConverter.ToString(response, dataStart, dataLength);                nextMib = conn.GetNextMIB(response);                if (!(nextMib.Substring(0, orgMibLength) == mib))                {                    break;                }                Console.WriteLine("{0}={1}", nextMib, value);            }        }        #endregion    }}

SNMP Class
复制  保存
using System;using System.Net;using System.Net.Sockets;using System.Text;namespace MACAddress{    /// <summary>    /// SNMP 的摘要描述。    /// </summary>    public class SNMP    {        public SNMP()        {        }        public byte[] Get(string request, string host, string community, string mibString)        {            byte[] packet = new byte[1024];            byte[] mib = new byte[1024];            int snmpLen;            int comLen = community.Length;            string[] mibVals = mibString.Split('.');            int mibLen = mibVals.Length;            int cnt = 0;            int temp;            int orgmibLen = mibLen;            int pos = 0;            for (int i = 0; i < orgmibLen; i++)            {                temp = Convert.ToInt16(mibVals[i]);                if (temp > 127)                {                    mib[cnt] = Convert.ToByte(128 + (temp / 128));                    mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));                    cnt += 2;                    mibLen++;                }                else                {                    mib[cnt] = Convert.ToByte(temp);                    cnt++;                }            }            snmpLen = 29 + comLen + mibLen - 1;            packet[pos++] = 0x30;            packet[pos++] = Convert.ToByte(snmpLen - 2);            packet[pos++] = 0x02;            packet[pos++] = 0x01;            packet[pos++] = 0x00;            packet[pos++] = 0x04;            packet[pos++] = Convert.ToByte(comLen);            byte[] data = Encoding.ASCII.GetBytes(community);            for (int i = 0; i < data.Length; i++)            {                packet[pos++] = data[i];            }            if (request == "get")            {                packet[pos++] = 0xA0;            }            else            {                packet[pos++] = 0xA1;            }            packet[pos++] = Convert.ToByte(20 + mibLen - 1);            packet[pos++] = 0x02;            packet[pos++] = 0x04;            packet[pos++] = 0x00;            packet[pos++] = 0x00;            packet[pos++] = 0x00;            packet[pos++] = 0x01;            packet[pos++] = 0x02;            packet[pos++] = 0x01;            packet[pos++] = 0x00;            packet[pos++] = 0x02;            packet[pos++] = 0x01;            packet[pos++] = 0x00;            packet[pos++] = 0x30;            packet[pos++] = Convert.ToByte(6 + mibLen - 1);            packet[pos++] = 0x30;            packet[pos++] = Convert.ToByte(6 + mibLen - 1 - 2);            packet[pos++] = 0x06;            packet[pos++] = Convert.ToByte(mibLen - 1);            packet[pos++] = 0x2b;            for (int i = 2; i < mibLen; i++)            {                packet[pos++] = Convert.ToByte(mib[i]);            }            packet[pos++] = 0x05;            packet[pos++] = 0x00;            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);            IPHostEntry ihe = Dns.Resolve(host);            IPEndPoint iep = new IPEndPoint(ihe.AddressList[0], 161);            EndPoint ep = (EndPoint) iep;            sock.SendTo(packet, snmpLen, SocketFlags.None, iep);            try            {                int recv = sock.ReceiveFrom(packet, ref ep);            }            catch (SocketException)            {                packet[0] = 0xff;            }            return packet;        }        public string GetNextMIB(byte[] mibIn)        {            string output = "1.3";            int commLength = mibIn[6];            int mibStart = 6 + commLength + 17;            int mibLength = mibIn[mibStart] - 1;            mibStart += 2;            int mibValue;            for (int i = mibStart; i < mibStart + mibLength; i++)            {                mibValue = Convert.ToInt16(mibIn[i]);                if (mibValue > 128)                {                    mibValue = (mibValue / 128) * 128 + Convert.ToInt16(mibIn[i + 1]);                    i++;                }                output += "." + mibValue;            }            return output;        }    }}

如果还有其它方法,请告诉我。


复制  保存
public class MACAddress{    public MACAddress()    {        //         // TODO: 在此处添加构造函数逻辑         //     }    [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 static string GetRemoteMAC(string remoteIP)    {        string ReturnValue = "";        ProcessStartInfo psi = new ProcessStartInfo();        psi.FileName = "nbtstat.exe";        psi.RedirectStandardInput = false;        psi.RedirectStandardOutput = true;        psi.Arguments = "-A " + remoteIP;        psi.UseShellExecute = false;        Process ps = Process.Start(psi);        string strEnd = ps.StandardOutput.ReadToEnd();        ps.WaitForExit();        string[] strs = strEnd.Split('/n');        foreach (string s in strs)        {            if (s.Trim().ToLower().IndexOf("mac address") != -1)            {                ReturnValue = s.Substring(s.IndexOf("Address =") + 10, 17);                break;            }        }        return ReturnValue;    }}
原创粉丝点击