【C#】获取机器码MachineCode

时间:2021-08-07 17:10:26

需求:机器码可以用于校验用户是否用的同一台电脑登录,比如在别的机器上登录时做强制下线(踢人下线)。通常在用户注册时,计算一次用户的机器码跟随注册信息一起发送给服务器。

机器码的作用看百度百科:

【C#】获取机器码MachineCode

定义规则:
机器码 = CPU序列号 + 硬盘ID + 网卡硬件地址

public class MachineCode
{

static MachineCode machineCode;

public static string GetMachineCodeString()
{
string machineCodeString = string.Empty;
if (machineCode == null)
{
machineCode = new MachineCode();
}
machineCodeString = "PC." + machineCode.GetCpuInfo() + "." +
machineCode.GetHDid() + "." +
machineCode.GetMoAddress();
return machineCodeString;
}

/// <summary>
/// 获取cpu序列号
/// </summary>
/// <returns> string </returns>
public string GetCpuInfo()
{
string cpuInfo = "";
try
{
using (ManagementClass cimobject = new ManagementClass("Win32_Processor"))
{
ManagementObjectCollection moc = cimobject.GetInstances();

foreach (ManagementObject mo in moc)
{
cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
mo.Dispose();
}
}
}
catch (Exception)
{
throw;
}
return cpuInfo.ToString();
}

/// <summary>
/// 获取硬盘ID
/// </summary>
/// <returns> string </returns>
public string GetHDid()
{
string HDid = "";
try
{
using (ManagementClass cimobject1 = new ManagementClass("Win32_DiskDrive"))
{
ManagementObjectCollection moc1 = cimobject1.GetInstances();
foreach (ManagementObject mo in moc1)
{
HDid = (string)mo.Properties["Model"].Value;
mo.Dispose();
}
}
}
catch (Exception)
{

throw;
}
return HDid.ToString();
}

/// <summary>
/// 获取网卡硬件地址
/// </summary>
/// <returns> string </returns>
public string GetMoAddress()
{
string MoAddress = "";
try
{
using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
{
ManagementObjectCollection moc2 = mc.GetInstances();
foreach (ManagementObject mo in moc2)
{
if ((bool)mo["IPEnabled"] == true)
MoAddress = mo["MacAddress"].ToString();
mo.Dispose();
}
}
}
catch (Exception)
{
throw;
}
return MoAddress.ToString();
}
}

原文地址:

http://group.cnblogs.com/topic/32913.html