获得MAC地址的四个方法
1.使用WMI。查询表Win32_NetworkAdapterConfiguration即可获得。
2.使用ARP协议。请看这里。
3.使用Windows命令nbtstat,也就是通过NetBIOS。请看这里。
4.查询SNMP(就是一种用于监视网络设备的协议)的MIB(管理信息数据库)。但这不是一件简单的事情,需要自己创建SNMP包,发送到交换机,然后对返回的响应进行解析。
下面是代碼:
 using System;
using System; using System.Diagnostics;
using System.Diagnostics; using System.Management;
using System.Management; using System.Net;
using System.Net; using System.Runtime.InteropServices;
using System.Runtime.InteropServices; using System.Text.RegularExpressions;
using System.Text.RegularExpressions;
 namespace MACAddress
namespace MACAddress {
{ /// <summary>
    /// <summary> /// MainClass 的摘要描述。
    /// MainClass 的摘要描述。 /// </summary>
    /// </summary> internal class MainClass
    internal class MainClass {
    { /// <summary>
        /// <summary> /// 應用程式的主進入點。
        /// 應用程式的主進入點。 /// </summary>
        /// </summary> [STAThread]
        [STAThread] private static void Main(string[] args)
        private static void Main(string[] args) {
        { GetMACByWMI();
            GetMACByWMI(); IPAddress[] ips = GetLocalIP();
            IPAddress[] ips = GetLocalIP(); foreach (IPAddress ip in ips)
            foreach (IPAddress ip in ips) {
            { Console.WriteLine(GetMacByARP(ip.ToString()));
                Console.WriteLine(GetMacByARP(ip.ToString())); string mac = GetRemoteMacByNetBIOS(ip.ToString());
                string mac = GetRemoteMacByNetBIOS(ip.ToString()); if ( mac.Length != 0 )
                if ( mac.Length != 0 ) Console.WriteLine(mac);
                    Console.WriteLine(mac); else
                else Console.WriteLine("Fail to get MACAddress by NetBIOS");
                    Console.WriteLine("Fail to get MACAddress by NetBIOS"); GetMACBySNMP(ip.ToString(),"yourGroupName@yourVlanNumber");
                GetMACBySNMP(ip.ToString(),"yourGroupName@yourVlanNumber"); }
            } Console.ReadLine();
            Console.ReadLine(); }
        }
 By WMI
        By WMI
 #region By ARP
        #region By ARP
 [DllImport("Iphlpapi.dll")]
        [DllImport("Iphlpapi.dll")] private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
 [DllImport("Ws2_32.dll")]
        [DllImport("Ws2_32.dll")] private static extern Int32 inet_addr(string ip);
        private static extern Int32 inet_addr(string ip);
 public static string GetMacByARP(string clientIP)
        public static string GetMacByARP(string clientIP) {
        { string ip = clientIP;
            string ip = clientIP; Int32 ldest = inet_addr(ip);
            Int32 ldest = inet_addr(ip); Int64 macinfo = new Int64();
            Int64 macinfo = new Int64(); Int32 len = 6;
            Int32 len = 6; try
            try {
            { SendARP(ldest, 0, ref macinfo, ref len);
                SendARP(ldest, 0, ref macinfo, ref len); }
            } catch
            catch {
            { return "";
                return ""; }
            } string originalMACAddress = Convert.ToString(macinfo, 16);
            string originalMACAddress = Convert.ToString(macinfo, 16); if (originalMACAddress.Length < 12)
            if (originalMACAddress.Length < 12) {
            { originalMACAddress = originalMACAddress.PadLeft(12, '0');
                originalMACAddress = originalMACAddress.PadLeft(12, '0'); }
            } string macAddress;
            string macAddress; if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
            if (originalMACAddress != "0000" && originalMACAddress.Length == 12) {
            { string mac1, mac2, mac3, mac4, mac5, mac6;
                string mac1, mac2, mac3, mac4, mac5, mac6; mac1 = originalMACAddress.Substring(10, 2);
                mac1 = originalMACAddress.Substring(10, 2); mac2 = originalMACAddress.Substring(8, 2);
                mac2 = originalMACAddress.Substring(8, 2); mac3 = originalMACAddress.Substring(6, 2);
                mac3 = originalMACAddress.Substring(6, 2); mac4 = originalMACAddress.Substring(4, 2);
                mac4 = originalMACAddress.Substring(4, 2); mac5 = originalMACAddress.Substring(2, 2);
                mac5 = originalMACAddress.Substring(2, 2); mac6 = originalMACAddress.Substring(0, 2);
                mac6 = originalMACAddress.Substring(0, 2); macAddress = mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6;
                macAddress = mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6; }
            } else
            else {
            { macAddress = "";
                macAddress = ""; }
            } return macAddress.ToUpper();
            return macAddress.ToUpper(); }
        }
 public static IPAddress[] GetLocalIP()
        public static IPAddress[] GetLocalIP() {
        { string hostName = Dns.GetHostName();
            string hostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostByName(hostName);
            IPHostEntry ipEntry = Dns.GetHostByName(hostName); return ipEntry.AddressList;
            return ipEntry.AddressList; }
        }
 #endregion
        #endregion
 #region By NetBIOS
        #region By NetBIOS public static string GetRemoteMacByNetBIOS(string clientIP)
        public static string GetRemoteMacByNetBIOS(string clientIP) {
        { string ip = clientIP;
            string ip = clientIP; string dirResults = "";
            string dirResults = ""; ProcessStartInfo psi = new ProcessStartInfo();
            ProcessStartInfo psi = new ProcessStartInfo(); Process proc = new Process();
            Process proc = new Process(); psi.FileName = "nbtstat.exe";
            psi.FileName = "nbtstat.exe"; //psi.RedirectStandardInput = false;
            //psi.RedirectStandardInput = false;  psi.RedirectStandardOutput = true;
            psi.RedirectStandardOutput = true; psi.RedirectStandardError = true;
            psi.RedirectStandardError = true; psi.Arguments = "-A " + ip;
            psi.Arguments = "-A " + ip; psi.UseShellExecute = false;
            psi.UseShellExecute = false; proc = Process.Start(psi);
            proc = Process.Start(psi); dirResults = proc.StandardOutput.ReadToEnd();
            dirResults = proc.StandardOutput.ReadToEnd(); string error = proc.StandardError.ReadToEnd();
            string error = proc.StandardError.ReadToEnd(); proc.WaitForExit();
            proc.WaitForExit(); dirResults = dirResults.Replace("\r", "").Replace("\n", "").Replace("\t", "");
            dirResults = dirResults.Replace("\r", "").Replace("\n", "").Replace("\t", ""); Regex reg = new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            Regex reg = new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC", RegexOptions.IgnoreCase | RegexOptions.Compiled); Match mc = reg.Match(dirResults + "__MAC");
            Match mc = reg.Match(dirResults + "__MAC"); if (mc.Success)
            if (mc.Success) {
            { return mc.Groups["key"].Value.ToUpper();
                return mc.Groups["key"].Value.ToUpper(); }
            } else
            else {
            { return "";
                return ""; }
            } }
        } #endregion
        #endregion
 #region By SNMP
        #region By SNMP public static void GetMACBySNMP(string ip,string vlan)
        public static void GetMACBySNMP(string ip,string vlan) {
        { int commLength,mibLength,dataStart,dataLength;
            int commLength,mibLength,dataStart,dataLength; string nextMib,value;
            string nextMib,value; SNMP conn = new SNMP();
            SNMP conn = new SNMP(); string mib = "1.3.6.1.2.1.17.4.3.1.1";
            string mib = "1.3.6.1.2.1.17.4.3.1.1"; int orgMibLength = mib.Length;
            int orgMibLength = mib.Length; byte[] response = new byte[1024];
            byte[] response = new byte[1024];
 nextMib = mib;
            nextMib = mib;
 while ( true)
            while ( true) {
            { response = conn.Get("getnext",ip,vlan,nextMib);
                response = conn.Get("getnext",ip,vlan,nextMib); commLength = Convert.ToInt16(response[6]);
                commLength = Convert.ToInt16(response[6]); mibLength = Convert.ToInt16(response[23+commLength]);
                mibLength = Convert.ToInt16(response[23+commLength]); dataLength = Convert.ToInt16(response[25+commLength+mibLength]);
                dataLength = Convert.ToInt16(response[25+commLength+mibLength]); dataStart = 26 + commLength + mibLength;
                dataStart = 26 + commLength + mibLength; value = BitConverter.ToString(response,dataStart,dataLength);
                value = BitConverter.ToString(response,dataStart,dataLength); nextMib = conn.GetNextMIB(response);
                nextMib = conn.GetNextMIB(response);
 if ( !(nextMib.Substring(0,orgMibLength) == mib))
                if ( !(nextMib.Substring(0,orgMibLength) == mib)) {
                { break;
                    break; }
                } Console.WriteLine("{0}={1}",nextMib,value);
                Console.WriteLine("{0}={1}",nextMib,value);
 }
            } }
        } #endregion
        #endregion }
    } }
}SNMP Class

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

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号