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;
![None.gif](/Images/OutliningIndicators/None.gif)
namespace
MACAddress
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// MainClass 的摘要描述。
/// </summary>
internal class MainClass
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
private static void Main(string[] args)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
GetMACByWMI();
IPAddress[] ips = GetLocalIP();
foreach (IPAddress ip in ips)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
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();
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
By WMI#region By WMI
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
public static void GetMACByWMI()
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
string query = "select MACAddress from Win32_NetworkAdapterConfiguration where IPEnabled='TRUE'";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject mo in collection)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
string mac = mo["MACAddress"].ToString();
Console.WriteLine(" Network card MAC Address is :{0}", mac);
}
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
#endregion
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
By ARP#region By ARP
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
public static string GetMacByARP(string clientIP)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
string ip = clientIP;
Int32 ldest = inet_addr(ip);
Int64 macinfo = new Int64();
Int32 len = 6;
try
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
SendARP(ldest, 0, ref macinfo, ref len);
}
catch
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return "";
}
string originalMACAddress = Convert.ToString(macinfo, 16);
if (originalMACAddress.Length < 12)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
originalMACAddress = originalMACAddress.PadLeft(12, '0');
}
string macAddress;
if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
string mac1, 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
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
macAddress = "";
}
return macAddress.ToUpper();
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
public static IPAddress[] GetLocalIP()
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
string hostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(hostName);
return ipEntry.AddressList;
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
#endregion
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
By NetBIOS#region By NetBIOS
public static string GetRemoteMacByNetBIOS(string clientIP)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
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)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return mc.Groups["key"].Value.ToUpper();
}
else
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
return "";
}
}
#endregion
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
By SNMP#region By SNMP
public static void GetMACBySNMP(string ip,string vlan)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
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];
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
nextMib = mib;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
while ( true)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
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);
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
if ( !(nextMib.Substring(0,orgMibLength) == mib))
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
break;
}
Console.WriteLine("{0}={1}",nextMib,value);
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
}
}
#endregion
}
}
SNMP Class
using
System;
using
System.Net;
using
System.Net.Sockets;
using
System.Text;
![None.gif](/Images/OutliningIndicators/None.gif)
namespace
MACAddress
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
/**//**//**//// <summary>
/// SNMP 的摘要描述。
/// </summary>
public class SNMP
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
public SNMP()
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
public byte[] Get(string request, string host, string community, string mibString)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
byte[] packet = new byte[1024];
byte[] mib = new byte[1024];
int snmpLen;
int comLen = community.Length;
string[] mibVals = mibString.Split('.');
int mibLen = mibVals.Length;
int cnt = 0;
int temp;
int orgmibLen = mibLen;
int pos = 0;
for (int i = 0; i < orgmibLen; i++)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
temp = Convert.ToInt16(mibVals[i]);
if (temp > 127)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
mib[cnt] = Convert.ToByte(128 + (temp / 128));
mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));
cnt += 2;
mibLen++;
}
else
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
mib[cnt] = Convert.ToByte(temp);
cnt++;
}
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
snmpLen = 29 + comLen + mibLen - 1;
packet[pos++] = 0x30;
packet[pos++] = Convert.ToByte(snmpLen - 2);
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
packet[pos++] = 0x02;
packet[pos++] = 0x01;
packet[pos++] = 0x00;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
packet[pos++] = 0x04;
packet[pos++] = Convert.ToByte(comLen);
byte[] data = Encoding.ASCII.GetBytes(community);
for (int i = 0; i < data.Length; i++)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
packet[pos++] = data[i];
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
if (request == "get")
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
packet[pos++] = 0xA0;
}
else
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
packet[pos++] = 0xA1;
}
packet[pos++] = Convert.ToByte(20 + mibLen - 1);
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
packet[pos++] = 0x02;
packet[pos++] = 0x04;
packet[pos++] = 0x00;
packet[pos++] = 0x00;
packet[pos++] = 0x00;
packet[pos++] = 0x01;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
packet[pos++] = 0x02;
packet[pos++] = 0x01;
packet[pos++] = 0x00;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
packet[pos++] = 0x02;
packet[pos++] = 0x01;
packet[pos++] = 0x00;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
packet[pos++] = 0x30;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
packet[pos++] = Convert.ToByte(6 + mibLen - 1);
packet[pos++] = 0x30;
packet[pos++] = Convert.ToByte(6 + mibLen - 1 - 2);
packet[pos++] = 0x06;
packet[pos++] = Convert.ToByte(mibLen - 1);
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
packet[pos++] = 0x2b;
for (int i = 2; i < mibLen; i++)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
packet[pos++] = Convert.ToByte(mib[i]);
}
packet[pos++] = 0x05;
packet[pos++] = 0x00;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
IPHostEntry ihe = Dns.Resolve(host);
IPEndPoint iep = new IPEndPoint(ihe.AddressList[0], 161);
EndPoint ep = (EndPoint) iep;
sock.SendTo(packet, snmpLen, SocketFlags.None, iep);
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
try
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
int recv = sock.ReceiveFrom(packet, ref ep);
}
catch (SocketException)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
packet[0] = 0xff;
}
return packet;
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
public string GetNextMIB(byte[] mibIn)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
string output = "1.3";
int commLength = mibIn[6];
int mibStart = 6 + commLength + 17;
int mibLength = mibIn[mibStart] - 1;
mibStart += 2;
int mibValue;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
for (int i = mibStart; i < mibStart + mibLength; i++)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
mibValue = Convert.ToInt16(mibIn[i]);
if (mibValue > 128)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
mibValue = (mibValue / 128) * 128 + Convert.ToInt16(mibIn[i + 1]);
i++;
}
output += "." + mibValue;
}
return output;
}
}
}
如果还有其它方法,请告诉我。