获得MAC地址的四个方法

 

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

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

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

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

下面是代碼:

None.gif using  System;
None.gif
using  System.Diagnostics;
None.gif
using  System.Management;
None.gif
using  System.Net;
None.gif
using  System.Runtime.InteropServices;
None.gif
using  System.Text.RegularExpressions;
None.gif
None.gif
namespace  MACAddress
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// MainClass 的摘要描述。
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    internal class MainClass
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 應用程式的主進入點。
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [STAThread]
InBlock.gif        
private static void Main(string[] args)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            GetMACByWMI();
InBlock.gif            IPAddress[] ips 
= GetLocalIP();
InBlock.gif            
foreach (IPAddress ip in ips)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Console.WriteLine(GetMacByARP(ip.ToString()));
InBlock.gif                
string mac = GetRemoteMacByNetBIOS(ip.ToString());
InBlock.gif                
if ( mac.Length != 0 )
InBlock.gif                    Console.WriteLine(mac);
InBlock.gif                
else
InBlock.gif                    Console.WriteLine(
"Fail to get MACAddress by NetBIOS");
InBlock.gif                GetMACBySNMP(ip.ToString(),
"yourGroupName@yourVlanNumber");
ExpandedSubBlockEnd.gif            }

InBlock.gif            Console.ReadLine();
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
By WMI#region By WMI
InBlock.gif
InBlock.gif        
public static void GetMACByWMI()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string query = "select MACAddress from Win32_NetworkAdapterConfiguration where IPEnabled='TRUE'";
InBlock.gif            ManagementObjectSearcher searcher 
= new ManagementObjectSearcher(query);
InBlock.gif            ManagementObjectCollection collection 
= searcher.Get();
InBlock.gif            
foreach (ManagementObject mo in collection)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string mac = mo["MACAddress"].ToString();
InBlock.gif                Console.WriteLine(
" Network card MAC Address is :{0}", mac);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
By ARP#region By ARP
InBlock.gif
InBlock.gif        [DllImport(
"Iphlpapi.dll")]
InBlock.gif        
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
InBlock.gif
InBlock.gif        [DllImport(
"Ws2_32.dll")]
InBlock.gif        
private static extern Int32 inet_addr(string ip);
InBlock.gif
InBlock.gif        
public static string GetMacByARP(string clientIP)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string ip = clientIP;
InBlock.gif            Int32 ldest 
= inet_addr(ip);
InBlock.gif            Int64 macinfo 
= new Int64();
InBlock.gif            Int32 len 
= 6;
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                SendARP(ldest, 
0ref macinfo, ref len);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return "";
ExpandedSubBlockEnd.gif            }

InBlock.gif            
string originalMACAddress = Convert.ToString(macinfo, 16);
InBlock.gif            
if (originalMACAddress.Length < 12)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                originalMACAddress 
= originalMACAddress.PadLeft(12'0');
ExpandedSubBlockEnd.gif            }

InBlock.gif            
string macAddress;
InBlock.gif            
if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string mac1, mac2, mac3, mac4, mac5, mac6;
InBlock.gif                mac1 
= originalMACAddress.Substring(102);
InBlock.gif                mac2 
= originalMACAddress.Substring(82);
InBlock.gif                mac3 
= originalMACAddress.Substring(62);
InBlock.gif                mac4 
= originalMACAddress.Substring(42);
InBlock.gif                mac5 
= originalMACAddress.Substring(22);
InBlock.gif                mac6 
= originalMACAddress.Substring(02);
InBlock.gif                macAddress 
= mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                macAddress 
= "";
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return macAddress.ToUpper();
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public static IPAddress[] GetLocalIP()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string hostName = Dns.GetHostName();
InBlock.gif            IPHostEntry ipEntry 
= Dns.GetHostByName(hostName);
InBlock.gif            
return ipEntry.AddressList;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
By NetBIOS#region By NetBIOS
InBlock.gif        
public static string GetRemoteMacByNetBIOS(string clientIP)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string ip = clientIP;
InBlock.gif            
string dirResults = "";
InBlock.gif            ProcessStartInfo psi 
= new ProcessStartInfo();
InBlock.gif            Process proc 
= new Process();
InBlock.gif            psi.FileName 
= "nbtstat.exe";
InBlock.gif            
//psi.RedirectStandardInput = false; 
InBlock.gif
            psi.RedirectStandardOutput = true;
InBlock.gif            psi.RedirectStandardError 
= true;
InBlock.gif            psi.Arguments 
= "-A " + ip;
InBlock.gif            psi.UseShellExecute 
= false;
InBlock.gif            proc 
= Process.Start(psi);
InBlock.gif            dirResults 
= proc.StandardOutput.ReadToEnd();
InBlock.gif            
string error = proc.StandardError.ReadToEnd();
InBlock.gif            proc.WaitForExit();
InBlock.gif            dirResults 
= dirResults.Replace("\r""").Replace("\n""").Replace("\t""");
InBlock.gif            Regex reg 
= new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC", RegexOptions.IgnoreCase | RegexOptions.Compiled);
InBlock.gif            Match mc 
= reg.Match(dirResults + "__MAC");
InBlock.gif            
if (mc.Success)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return mc.Groups["key"].Value.ToUpper();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return "";
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
By SNMP#region By SNMP
InBlock.gif        
public static void GetMACBySNMP(string ip,string vlan)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
int commLength,mibLength,dataStart,dataLength;
InBlock.gif            
string nextMib,value;
InBlock.gif            SNMP conn 
= new SNMP();
InBlock.gif            
string mib = "1.3.6.1.2.1.17.4.3.1.1";
InBlock.gif            
int orgMibLength = mib.Length;
InBlock.gif            
byte[] response = new byte[1024];
InBlock.gif
InBlock.gif            nextMib 
= mib;
InBlock.gif
InBlock.gif            
while ( true)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                response 
= conn.Get("getnext",ip,vlan,nextMib);
InBlock.gif                commLength 
= Convert.ToInt16(response[6]);
InBlock.gif                mibLength 
= Convert.ToInt16(response[23+commLength]);
InBlock.gif                dataLength 
= Convert.ToInt16(response[25+commLength+mibLength]);
InBlock.gif                dataStart 
= 26 + commLength + mibLength;
InBlock.gif                value 
= BitConverter.ToString(response,dataStart,dataLength);
InBlock.gif                nextMib 
= conn.GetNextMIB(response);
InBlock.gif
InBlock.gif                
if ( !(nextMib.Substring(0,orgMibLength) == mib))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
break;
ExpandedSubBlockEnd.gif                }

InBlock.gif                Console.WriteLine(
"{0}={1}",nextMib,value);
InBlock.gif
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


SNMP Class

None.gif
None.gif
using  System;
None.gif
using  System.Net;
None.gif
using  System.Net.Sockets;
None.gif
using  System.Text;
None.gif
None.gif
namespace  MACAddress
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//**//**//// <summary>
InBlock.gif    
/// SNMP 的摘要描述。
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class SNMP
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public SNMP()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public byte[] Get(string request, string host, string community, string mibString)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
byte[] packet = new byte[1024];
InBlock.gif            
byte[] mib = new byte[1024];
InBlock.gif            
int snmpLen;
InBlock.gif            
int comLen = community.Length;
InBlock.gif            
string[] mibVals = mibString.Split('.');
InBlock.gif            
int mibLen = mibVals.Length;
InBlock.gif            
int cnt = 0;
InBlock.gif            
int temp;
InBlock.gif            
int orgmibLen = mibLen;
InBlock.gif            
int pos = 0;
InBlock.gif            
for (int i = 0; i < orgmibLen; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                temp 
= Convert.ToInt16(mibVals[i]);
InBlock.gif                
if (temp > 127)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    mib[cnt] 
= Convert.ToByte(128 + (temp / 128));
InBlock.gif                    mib[cnt 
+ 1= Convert.ToByte(temp - ((temp / 128* 128));
InBlock.gif                    cnt 
+= 2;
InBlock.gif                    mibLen
++;
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    mib[cnt] 
= Convert.ToByte(temp);
InBlock.gif                    cnt
++;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            snmpLen 
= 29 + comLen + mibLen - 1;
InBlock.gif            packet[pos
++= 0x30;
InBlock.gif            packet[pos
++= Convert.ToByte(snmpLen - 2);
InBlock.gif
InBlock.gif            packet[pos
++= 0x02;
InBlock.gif            packet[pos
++= 0x01;
InBlock.gif            packet[pos
++= 0x00;
InBlock.gif
InBlock.gif            packet[pos
++= 0x04;
InBlock.gif            packet[pos
++= Convert.ToByte(comLen);
InBlock.gif            
byte[] data = Encoding.ASCII.GetBytes(community);
InBlock.gif            
for (int i = 0; i < data.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                packet[pos
++= data[i];
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (request == "get")
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                packet[pos
++= 0xA0;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                packet[pos
++= 0xA1;
ExpandedSubBlockEnd.gif            }

InBlock.gif            packet[pos
++= Convert.ToByte(20 + mibLen - 1);
InBlock.gif
InBlock.gif            packet[pos
++= 0x02;
InBlock.gif            packet[pos
++= 0x04;
InBlock.gif            packet[pos
++= 0x00;
InBlock.gif            packet[pos
++= 0x00;
InBlock.gif            packet[pos
++= 0x00;
InBlock.gif            packet[pos
++= 0x01;
InBlock.gif
InBlock.gif            packet[pos
++= 0x02;
InBlock.gif            packet[pos
++= 0x01;
InBlock.gif            packet[pos
++= 0x00;
InBlock.gif
InBlock.gif            packet[pos
++= 0x02;
InBlock.gif            packet[pos
++= 0x01;
InBlock.gif            packet[pos
++= 0x00;
InBlock.gif
InBlock.gif            packet[pos
++= 0x30;
InBlock.gif
InBlock.gif            packet[pos
++= Convert.ToByte(6 + mibLen - 1);
InBlock.gif            packet[pos
++= 0x30;
InBlock.gif            packet[pos
++= Convert.ToByte(6 + mibLen - 1 - 2);
InBlock.gif            packet[pos
++= 0x06;
InBlock.gif            packet[pos
++= Convert.ToByte(mibLen - 1);
InBlock.gif
InBlock.gif            packet[pos
++= 0x2b;
InBlock.gif            
for (int i = 2; i < mibLen; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                packet[pos
++= Convert.ToByte(mib[i]);
ExpandedSubBlockEnd.gif            }

InBlock.gif            packet[pos
++= 0x05;
InBlock.gif            packet[pos
++= 0x00;
InBlock.gif
InBlock.gif            Socket sock 
= new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
InBlock.gif            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 
5000);
InBlock.gif            IPHostEntry ihe 
= Dns.Resolve(host);
InBlock.gif            IPEndPoint iep 
= new IPEndPoint(ihe.AddressList[0], 161);
InBlock.gif            EndPoint ep 
= (EndPoint) iep;
InBlock.gif            sock.SendTo(packet, snmpLen, SocketFlags.None, iep);
InBlock.gif
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
int recv = sock.ReceiveFrom(packet, ref ep);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (SocketException)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                packet[
0= 0xff;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return packet;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public string GetNextMIB(byte[] mibIn)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string output = "1.3";
InBlock.gif            
int commLength = mibIn[6];
InBlock.gif            
int mibStart = 6 + commLength + 17;
InBlock.gif            
int mibLength = mibIn[mibStart] - 1;
InBlock.gif            mibStart 
+= 2;
InBlock.gif            
int mibValue;
InBlock.gif
InBlock.gif            
for (int i = mibStart; i < mibStart + mibLength; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                mibValue 
= Convert.ToInt16(mibIn[i]);
InBlock.gif                
if (mibValue > 128)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    mibValue 
= (mibValue / 128* 128 + Convert.ToInt16(mibIn[i + 1]);
InBlock.gif                    i
++;
ExpandedSubBlockEnd.gif                }

InBlock.gif                output 
+= "." + mibValue;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return output;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值