现在的位置: 首页 > 综合 > 正文

获得MAC地址的四个方法

2013年08月17日 ⁄ 综合 ⁄ 共 5582字 ⁄ 字号 评论关闭
 http://jiezhi.cnblogs.com/archive/2005/07/13/192066.html(转)

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

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

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

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();
        }


        
By WMI

        
#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, 
0ref 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(102);
                mac2 
= originalMACAddress.Substring(82);
                mac3 
= originalMACAddress.Substring(62);
                mac4 
= originalMACAddress.Substring(42);
                mac5 
= originalMACAddress.Substring(22);
                mac6 
= originalMACAddress.Substring(02);
                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 

抱歉!评论已关闭.