using System;
using System.Collections;
using System.Diagnostics;
using System.Management;
using System.Net;
using System.DirectoryServices;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
获得本机的MAC地址
public static string GetLocalMac()
{
string strMac = string.Empty;
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach(ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
strMac += mo["MacAddress"].ToString() ;
}
return strMac.ToUpper();
}
获得远程计算机的MAC地址
方法一:使用API,利用ARP协议,只能获得同网段计算机的MAC
[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 GetRemoteMac(string clientIP)
{
string ip = clientIP;
if ( ip == "127.0.0.1")
ip = GetLocalIP()[0];
Int32 ldest=inet_addr(ip);
Int64 macinfo=new Int64();
Int32 len=6;
try
{
SendARP(ldest,0,ref macinfo,ref len);
}
catch
{
return "";
}
string originalMACAddress = Convert.ToString(macinfo,16);