获得MAC地址的四个方法

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>

internalclassMainClass
{
/**////<summary>
///應用程式的主進入點。
///</summary>

[STAThread]
privatestaticvoidMain(string[]args)
{
GetMACByWMI();
IPAddress[]ips
=GetLocalIP();
foreach(IPAddressipinips)
{
Console.WriteLine(GetMacByARP(ip.ToString()));
stringmac=GetRemoteMacByNetBIOS(ip.ToString());
if(mac.Length!=0)
Console.WriteLine(mac);
else
Console.WriteLine(
"FailtogetMACAddressbyNetBIOS");
GetMACBySNMP(ip.ToString(),
"yourGroupName@yourVlanNumber");
}

Console.ReadLine();
}


ByWMI#regionByWMI

publicstaticvoidGetMACByWMI()
{
stringquery="selectMACAddressfromWin32_NetworkAdapterConfigurationwhereIPEnabled='TRUE'";
ManagementObjectSearchersearcher
=newManagementObjectSearcher(query);
ManagementObjectCollectioncollection
=searcher.Get();
foreach(ManagementObjectmoincollection)
{
stringmac=mo["MACAddress"].ToString();
Console.WriteLine(
"NetworkcardMACAddressis:{0}",mac);
}

}


#endregion


ByARP#regionByARP

[DllImport(
"Iphlpapi.dll")]
privatestaticexternintSendARP(Int32dest,Int32host,refInt64mac,refInt32length);

[DllImport(
"Ws2_32.dll")]
privatestaticexternInt32inet_addr(stringip);

publicstaticstringGetMacByARP(stringclientIP)
{
stringip=clientIP;
Int32ldest
=inet_addr(ip);
Int64macinfo
=newInt64();
Int32len
=6;
try
{
SendARP(ldest,
0,refmacinfo,reflen);
}

catch
{
return"";
}

stringoriginalMACAddress=Convert.ToString(macinfo,16);
if(originalMACAddress.Length<12)
{
originalMACAddress
=originalMACAddress.PadLeft(12,'0');
}

stringmacAddress;
if(originalMACAddress!="0000"&&originalMACAddress.Length==12)
{
stringmac1,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
="";
}

returnmacAddress.ToUpper();
}


publicstaticIPAddress[]GetLocalIP()
{
stringhostName=Dns.GetHostName();
IPHostEntryipEntry
=Dns.GetHostByName(hostName);
returnipEntry.AddressList;
}


#endregion


ByNetBIOS#regionByNetBIOS
publicstaticstringGetRemoteMacByNetBIOS(stringclientIP)
{
stringip=clientIP;
stringdirResults="";
ProcessStartInfopsi
=newProcessStartInfo();
Processproc
=newProcess();
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();
stringerror=proc.StandardError.ReadToEnd();
proc.WaitForExit();
dirResults
=dirResults.Replace("\r","").Replace("\n","").Replace("\t","");
Regexreg
=newRegex("Mac[]{0,}Address[]{0,}=[]{0,}(?((.)*?))__MAC",RegexOptions.IgnoreCase|RegexOptions.Compiled);
Matchmc
=reg.Match(dirResults+"__MAC");
if(mc.Success)
{
returnmc.Groups["key"].Value.ToUpper();
}

else
{
return"";
}

}

#endregion


BySNMP#regionBySNMP
publicstaticvoidGetMACBySNMP(stringip,stringvlan)
{
intcommLength,mibLength,dataStart,dataLength;
stringnextMib,value;
SNMPconn
=newSNMP();
stringmib="1.3.6.1.2.1.17.4.3.1.1";
intorgMibLength=mib.Length;
byte[]response=newbyte[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>

publicclassSNMP
{
publicSNMP()
{
}


publicbyte[]Get(stringrequest,stringhost,stringcommunity,stringmibString)
{
byte[]packet=newbyte[1024];
byte[]mib=newbyte[1024];
intsnmpLen;
intcomLen=community.Length;
string[]mibVals=mibString.Split('.');
intmibLen=mibVals.Length;
intcnt=0;
inttemp;
intorgmibLen=mibLen;
intpos=0;
for(inti=0;i<orgmibLen;i++)
{
temp
=Convert.ToInt16(mibVals[i]);
if(temp>127)
分享到:
评论

你可能感兴趣的:(.net,windows,网络协议)