获得MAC地址的四个方法

1.使用WMI查询表Win32_NetworkAdapterConfiguration即可获得。

2.使用ARP协议。请看这里

3.使用Windows命令nbtstat,也就是通过NetBIOS请看这里

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

下面是代碼:

  1. using System;
  2. using System.Diagnostics;
  3. using System.Management;
  4. using System.Net;
  5. using System.Runtime.InteropServices;
  6. using System.Text.RegularExpressions;
  7. namespace MACAddress
  8. {
  9.     /**//// <summary>
  10.     /// MainClass 的摘要描述。
  11.     /// </summary>
  12.     internal class MainClass
  13.     {
  14.         /**//// <summary>
  15.         /// 應用程式的主進入點。
  16.         /// </summary>
  17.         [STAThread]
  18.         private static void Main(string[] args)
  19.         {
  20.             GetMACByWMI();
  21.             IPAddress[] ips = GetLocalIP();
  22.             foreach (IPAddress ip in ips)
  23.             {
  24.                 Console.WriteLine(GetMacByARP(ip.ToString()));
  25.                 string mac = GetRemoteMacByNetBIOS(ip.ToString());
  26.                 if ( mac.Length != 0 )
  27.                     Console.WriteLine(mac);
  28.                 else
  29.                     Console.WriteLine("Fail to get MACAddress by NetBIOS");
  30.                 GetMACBySNMP(ip.ToString(),"yourGroupName@yourVlanNumber");
  31.             }
  32.             Console.ReadLine();
  33.         }
  34.         By WMI#region By WMI
  35.         public static void GetMACByWMI()
  36.         {
  37.             string query = "select MACAddress from Win32_NetworkAdapterConfiguration where IPEnabled='TRUE'";
  38.             ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
  39.             ManagementObjectCollection collection = searcher.Get();
  40.             foreach (ManagementObject mo in collection)
  41.             {
  42.                 string mac = mo["MACAddress"].ToString();
  43.                 Console.WriteLine(" Network card MAC Address is :{0}", mac);
  44.             }
  45.         }
  46.         #endregion
  47.         By ARP#region By ARP
  48.         [DllImport("Iphlpapi.dll")]
  49.         private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
  50.         [DllImport("Ws2_32.dll")]
  51.         private static extern Int32 inet_addr(string ip);
  52.         public static string GetMacByARP(string clientIP)
  53.         {
  54.             string ip = clientIP;
  55.             Int32 ldest = inet_addr(ip);
  56.             Int64 macinfo = new Int64();
  57.             Int32 len = 6;
  58.             try
  59.             {
  60.                 SendARP(ldest, 0, ref macinfo, ref len);
  61.             }
  62.             catch
  63.             {
  64.                 return "";
  65.             }
  66.             string originalMACAddress = Convert.ToString(macinfo, 16);
  67.             if (originalMACAddress.Length < 12)
  68.             {
  69.                 originalMACAddress = originalMACAddress.PadLeft(12, '0');
  70.             }
  71.             string macAddress;
  72.             if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
  73.             {
  74.                 string mac1, mac2, mac3, mac4, mac5, mac6;
  75.                 mac1 = originalMACAddress.Substring(10, 2);
  76.                 mac2 = originalMACAddress.Substring(8, 2);
  77.                 mac3 = originalMACAddress.Substring(6, 2);
  78.                 mac4 = originalMACAddress.Substring(4, 2);
  79.                 mac5 = originalMACAddress.Substring(2, 2);
  80.                 mac6 = originalMACAddress.Substring(0, 2);
  81.                 macAddress = mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6;
  82.             }
  83.             else
  84.             {
  85.                 macAddress = "";
  86.             }
  87.             return macAddress.ToUpper();
  88.         }
  89.         public static IPAddress[] GetLocalIP()
  90.         {
  91.             string hostName = Dns.GetHostName();
  92.             IPHostEntry ipEntry = Dns.GetHostByName(hostName);
  93.             return ipEntry.AddressList;
  94.         }
  95.         #endregion
  96.         By NetBIOS#region By NetBIOS
  97.         public static string GetRemoteMacByNetBIOS(string clientIP)
  98.         {
  99.             string ip = clientIP;
  100.             string dirResults = "";
  101.             ProcessStartInfo psi = new ProcessStartInfo();
  102.             Process proc = new Process();
  103.             psi.FileName = "nbtstat.exe";
  104.             //psi.RedirectStandardInput = false; 
  105.             psi.RedirectStandardOutput = true;
  106.             psi.RedirectStandardError = true;
  107.             psi.Arguments = "-A " + ip;
  108.             psi.UseShellExecute = false;
  109.             proc = Process.Start(psi);
  110.             dirResults = proc.StandardOutput.ReadToEnd();
  111.             string error = proc.StandardError.ReadToEnd();
  112.             proc.WaitForExit();
  113.             dirResults = dirResults.Replace("/r""").Replace("/n""").Replace("/t""");
  114.             Regex reg = new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  115.             Match mc = reg.Match(dirResults + "__MAC");
  116.             if (mc.Success)
  117.             {
  118.                 return mc.Groups["key"].Value.ToUpper();
  119.             }
  120.             else
  121.             {
  122.                 return "";
  123.             }
  124.         }
  125.         #endregion
  126.         By SNMP#region By SNMP
  127.         public static void GetMACBySNMP(string ip,string vlan)
  128.         {
  129.             int commLength,mibLength,dataStart,dataLength;
  130.             string nextMib,value;
  131.             SNMP conn = new SNMP();
  132.             string mib = "1.3.6.1.2.1.17.4.3.1.1";
  133.             int orgMibLength = mib.Length;
  134.             byte[] response = new byte[1024];
  135.             nextMib = mib;
  136.             while ( true)
  137.             {
  138.                 response = conn.Get("getnext",ip,vlan,nextMib);
  139.                 commLength = Convert.ToInt16(response[6]);
  140.                 mibLength = Convert.ToInt16(response[23+commLength]);
  141.                 dataLength = Convert.ToInt16(response[25+commLength+mibLength]);
  142.                 dataStart = 26 + commLength + mibLength;
  143.                 value = BitConverter.ToString(response,dataStart,dataLength);
  144.                 nextMib = conn.GetNextMIB(response);
  145.                 if ( !(nextMib.Substring(0,orgMibLength) == mib))
  146.                 {
  147.                     break;
  148.                 }
  149.                 Console.WriteLine("{0}={1}",nextMib,value);
  150.             }
  151.         }
  152.         #endregion
  153.     }
  154. }

 

 

SNMP Class

 

  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. namespace MACAddress
  6. {
  7.     /**//**//**//// <summary>
  8.     /// SNMP 的摘要描述。
  9.     /// </summary>
  10.     public class SNMP
  11.     {
  12.         public SNMP()
  13.         {
  14.         }
  15.         public byte[] Get(string request, string host, string community, string mibString)
  16.         {
  17.             byte[] packet = new byte[1024];
  18.             byte[] mib = new byte[1024];
  19.             int snmpLen;
  20.             int comLen = community.Length;
  21.             string[] mibVals = mibString.Split('.');
  22.             int mibLen = mibVals.Length;
  23.             int cnt = 0;
  24.             int temp;
  25.             int orgmibLen = mibLen;
  26.             int pos = 0;
  27.             for (int i = 0; i < orgmibLen; i++)
  28.             {
  29.                 temp = Convert.ToInt16(mibVals[i]);
  30.                 if (temp > 127)
  31.                 {
  32.                     mib[cnt] = Convert.ToByte(128 + (temp / 128));
  33.                     mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));
  34.                     cnt += 2;
  35.                     mibLen++;
  36.                 }
  37.                 else
  38.                 {
  39.                     mib[cnt] = Convert.ToByte(temp);
  40.                     cnt++;
  41.                 }
  42.             }
  43.             snmpLen = 29 + comLen + mibLen - 1;
  44.             packet[pos++] = 0x30;
  45.             packet[pos++] = Convert.ToByte(snmpLen - 2);
  46.             packet[pos++] = 0x02;
  47.             packet[pos++] = 0x01;
  48.             packet[pos++] = 0x00;
  49.             packet[pos++] = 0x04;
  50.             packet[pos++] = Convert.ToByte(comLen);
  51.             byte[] data = Encoding.ASCII.GetBytes(community);
  52.             for (int i = 0; i < data.Length; i++)
  53.             {
  54.                 packet[pos++] = data[i];
  55.             }
  56.             if (request == "get")
  57.             {
  58.                 packet[pos++] = 0xA0;
  59.             }
  60.             else
  61.             {
  62.                 packet[pos++] = 0xA1;
  63.             }
  64.             packet[pos++] = Convert.ToByte(20 + mibLen - 1);
  65.             packet[pos++] = 0x02;
  66.             packet[pos++] = 0x04;
  67.             packet[pos++] = 0x00;
  68.             packet[pos++] = 0x00;
  69.             packet[pos++] = 0x00;
  70.             packet[pos++] = 0x01;
  71.             packet[pos++] = 0x02;
  72.             packet[pos++] = 0x01;
  73.             packet[pos++] = 0x00;
  74.             packet[pos++] = 0x02;
  75.             packet[pos++] = 0x01;
  76.             packet[pos++] = 0x00;
  77.             packet[pos++] = 0x30;
  78.             packet[pos++] = Convert.ToByte(6 + mibLen - 1);
  79.             packet[pos++] = 0x30;
  80.             packet[pos++] = Convert.ToByte(6 + mibLen - 1 - 2);
  81.             packet[pos++] = 0x06;
  82.             packet[pos++] = Convert.ToByte(mibLen - 1);
  83.             packet[pos++] = 0x2b;
  84.             for (int i = 2; i < mibLen; i++)
  85.             {
  86.                 packet[pos++] = Convert.ToByte(mib[i]);
  87.             }
  88.             packet[pos++] = 0x05;
  89.             packet[pos++] = 0x00;
  90.             Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  91.             sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
  92.             IPHostEntry ihe = Dns.Resolve(host);
  93.             IPEndPoint iep = new IPEndPoint(ihe.AddressList[0], 161);
  94.             EndPoint ep = (EndPoint) iep;
  95.             sock.SendTo(packet, snmpLen, SocketFlags.None, iep);
  96.             try
  97.             {
  98.                 int recv = sock.ReceiveFrom(packet, ref ep);
  99.             }
  100.             catch (SocketException)
  101.             {
  102.                 packet[0] = 0xff;
  103.             }
  104.             return packet;
  105.         }
  106.         public string GetNextMIB(byte[] mibIn)
  107.         {
  108.             string output = "1.3";
  109.             int commLength = mibIn[6];
  110.             int mibStart = 6 + commLength + 17;
  111.             int mibLength = mibIn[mibStart] - 1;
  112.             mibStart += 2;
  113.             int mibValue;
  114.             for (int i = mibStart; i < mibStart + mibLength; i++)
  115.             {
  116.                 mibValue = Convert.ToInt16(mibIn[i]);
  117.                 if (mibValue > 128)
  118.                 {
  119.                     mibValue = (mibValue / 128) * 128 + Convert.ToInt16(mibIn[i + 1]);
  120.                     i++;
  121.                 }
  122.                 output += "." + mibValue;
  123.             }
  124.             return output;
  125.         }
  126.     }
  127. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值