/// <summary>
/// 获取硬盘序列号
/// </summary>
/// <returns></returns>
public static string getDiskSerialNum()
{
string result = "";
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
ManagementObjectCollection moCollection = searcher.Get();
foreach (ManagementObject mObject in moCollection)
{
result += mObject["SerialNumber"].ToString() + " ";
}
return result;
}
/// <summary>
/// 取得网卡的MAC地址
/// </summary>
public static IList<string> GetNetCardMacAddress()
{
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
IList<string> str = new List<string>();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
str.Add(mo["MacAddress"].ToString());
}
return str;
}
/// <summary>
/// 获取本机IPV4地址
/// </summary>
/// <returns></returns>
public static string getLocalIP()
{
string strIP = "127.0.0.1";
List<string> nicArray = getLocalAllIP();//获取所有IP后再筛选
if (nicArray.Count > 0)
{
foreach (string tmpNic in nicArray)
{
IPAddress ip = IPAddress.Parse(tmpNic);
if (ip.AddressFamily.ToString() == "InterNetwork") //ipv4,InterNetworkV6=ipv6
{
strIP = tmpNic;
break;
}
}
}
return strIP;
}
/// <summary>
/// 获取本机所有IP地址
/// </summary>
/// <returns></returns>
public static List<string> getLocalAllIP() { List<string> localAllIp = new List<string>(); ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection nics = mc.GetInstances(); foreach (ManagementObject
nic in nics) { if (Convert.ToBoolean(nic["IPEnabled"]) == true) { String[] nicArray = nic["IPAddress"] as String[]; localAllIp.AddRange(nicArray); } } return localAllIp; }
//根据远程IP地址获取该IP的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); //该函数只能取IPV4
/// <summary>
/// 获取远程MAC
/// </summary>
/// <param name="remoteIP"></param>
/// <returns></returns>
public static String getRemoteMAC(string remoteIP)
{
try
{
Int32 ldest = inet_addr(remoteIP); //目的地的ip
Int32 lhost = inet_addr(getLocalIP()); //本地ip
Int64 macinfo = new Int64();
Int32 len = 6;
int res = SendARP(ldest, 0, ref macinfo, ref len);
String x = Convert.ToString(macinfo, 16).padLeft(12,'0');//补齐12位
StringBuilder buffer = new StringBuilder(17);
buffer.Append(x.Substring(10, 2)).Append(':');
buffer.Append(x.Substring(8, 2)).Append(':');
buffer.Append(x.Substring(6, 2)).Append(':');
buffer.Append(x.Substring(4, 2)).Append(':');
buffer.Append(x.Substring(2, 2)).Append(':');
buffer.Append(x.Substring(0, 2));
return buffer.ToString();
}
catch (Exception err)
{
return null;
}
}