注意点,如果开发需要获取计算机的唯一编码,虽然MAC地址是比较常用的,但是建议用计算机的磁盘信息,因为有些电脑的MAC地址有多个,换个网口很容易混淆。
为什么不用CPUID:应为CPUID不是唯一的哟
主板信息也不推荐,应为有些电脑获取不到主板信息。
磁盘ID:只要是正版的,就是唯一的
直接上代码:
/// <summary>
/// 获取IPV4地址集合,就是获取本机所有的IPV4地址
/// </summary>
/// <returns></returns>
public static List<string> GetClientLocalIPv4AddressList()
{
List<string> ipAddressList = new List<string>();
try
{
IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
foreach (IPAddress ipAddress in ipHost.AddressList)
{
if (!ipAddressList.Contains(ipAddress.ToString()))
{
ipAddressList.Add(ipAddress.ToString());
}
}
}
catch
{
}
return ipAddressList;
}
/// <summary>
/// 获取计算机所有的MAC地址
/// </summary>
/// <returns></returns>
public string[] GetAllMacInfo()
{
List<string> LSMac = new List<string>();
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"]==true)
{
LSMac.Add(mo["MacAddress"].ToString().Replace(":",""));
}
}
mc = null;
moc = null;
return LSMac.ToArray() ;
}
///<summary>
/// 根据IP获取MAC地址
///</summary>
///<param name="RemoteIP">目标机器的IP地址如(192.168.1.1)</param>
///<returns>目标机器的mac 地址</returns>
public string GetMacAddress(string RemoteIP)
{
StringBuilder macAddress = new StringBuilder();
try
{
Int32 remote = inet_addr(RemoteIP);
Int64 macInfo = new Int64();
Int32 length = 6;
SendARP(remote, 0, ref macInfo, ref length);
string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
int x = 12;
for (int i = 0; i < 6; i++)
{
if (i == 5)
{
macAddress.Append(temp.Substring(x - 2, 2));
}
else
{
macAddress.Append(temp.Substring(x - 2, 2));
}
x -= 2;
}
return macAddress.ToString();
}
catch
{
return macAddress.ToString();
}
}
/// <summary>
/// 获取CpuID
/// </summary>
/// <returns>CpuID</returns>
public static string GetCpuID()
{
try
{
string strCpuID = string.Empty;
ManagementClass mc = new ManagementClass("Win32_Processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
strCpuID = mo.Properties["ProcessorId"].Value.ToString();
}
moc = null;
mc = null;
return strCpuID;
}
catch
{
return "unknown";
}
}
/// <summary>
/// 获取硬盘ID
/// </summary>
/// <returns></returns>
public static string GetDiskID()
{
ManagementClass mc = new ManagementClass("Win32_PhysicalMedia");
//网上有提到,用Win32_DiskDrive,但是用Win32_DiskDrive获得的硬盘信息中并不包含SerialNumber属性。
ManagementObjectCollection moc = mc.GetInstances();
string strID = null;
foreach (ManagementObject mo in moc)
{
strID = mo.Properties["SerialNumber"].Value.ToString();
break;
}
return strID;
}
/// <summary>
/// 获取主板ID
/// </summary>
/// <returns></returns>
public static string GetMainBordID()
{
ManagementClass mc = new ManagementClass("Win32_BaseBoard");
ManagementObjectCollection moc = mc.GetInstances();
string strID = null;
foreach (ManagementObject mo in moc)
{
strID = mo.Properties["SerialNumber"].Value.ToString();
break;
}
return strID;
}