C# 获取ipv4 ip 地址和电脑MAC 地址源代码
C# 获取ipv4 ip 地址和电脑MAC 地址源代码
很多时候我们需要获取电脑的ip地址对程序就行权限的判断,还有电脑mac地址对电脑的锁定,这个时候 ,我们就要获取电脑ipv4 和mac 地址。
下面就是获取IP地址和 Mac 地址的源代码
/// <summary>
/// <summary>
/// 获取ip 地址
/// </summary>
/// <returns></returns>
public static string GetMyIP()
{
IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
string ip = string.Empty;
Regex reg = new Regex(@"\d+\.\d+\.\d+\.\d+");
foreach (var strip in IpEntry.AddressList)
{
if (reg.IsMatch(strip.ToString()))
{
ip = strip.ToString();
}
}
return ip;
}
/// <summary>
/// 获取MAC地址(返回第一个物理以太网卡的mac地址)
/// </summary>
/// <returns>成功返回mac地址,失败返回null</returns>
public static string getMacAddress()
{
string macAddress = null;
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType.ToString().Equals("Ethernet")) //是以太网卡
{
string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
// 区分 PnpInstanceID
// 如果前面有 PCI 就是本机的真实网卡
// MediaSubType 为 01 则是常见网卡,02为无线网卡。
string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI") //是物理网卡
{
macAddress = adapter.GetPhysicalAddress().ToString();
break;
}
else if (fMediaSubType == 1) //虚拟网卡
continue;
else if (fMediaSubType == 2) //无线网卡(上面判断Ethernet时已经排除了)
continue;
}
}
}
}
catch
{
macAddress = null;
}
return macAddress;
}
原文链接:http://www.jxszl.com/jlmb/Others/23991.html