协助获取本机hostname、ipv4、Mac地址信息,用于记录用户日志
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
namespace ServiceDesk.classLibs
{
class MachineAssistant
{
//代码作者:一起种梧桐吧(数字技术研发部)
//创建日期:2024年10月19日
//备注信息:用于获取客户端信息的辅助处理
//插件信息:
private string Hostname { get; set; }
private string Ip4 { get; set; }
private string Mac { get; set; }
public string Info { get; set; }
public MachineAssistant()
{
Hostname = getHostname();
Ip4 = getIp4();
Mac = getMac();
List<string> ls = new List<string>(3);
ls.Add(Hostname);
ls.Add(Ip4);
ls.Add(Mac);
Info = StringAssistant.stringConcat(ls);
}
// 获取本机hostname
private static string getHostname()
{
string hostname = "hostname";
try
{
hostname = Dns.GetHostName();
}
catch (Exception)
{
hostname = "Error Hostname";
}
return hostname;
}
// 通过主机名解析ipv4
private static string getIp4FromDns()
{
string ip4 = null;
string addr = null;
try
{
// 尝试解析主机名
IPAddress[] addresses = Dns.GetHostAddresses(getHostname());
foreach (IPAddress address in addresses)
{
addr += "\t" + address.ToString();
}
}
catch (Exception e)
{
ip4 = "DNS查询失败: " + e.Message;
}
if (addr != null)
{
string pattern = @"\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";
MatchCollection matches = Regex.Matches(addr, pattern);
foreach (Match match in matches)
{
ip4 = match.Value;
break;
}
}
return ip4;
}
// 通过网络接口获取本机ipv4
private static string getIp4()
{
string ip4 = "127.0.0.1";
// 获取本机所有网络接口
try
{
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in networkInterfaces)
{
// 忽略没有运行或没有IP配置的网络接口
if (ni.OperationalStatus != OperationalStatus.Up || ni.NetworkInterfaceType == NetworkInterfaceType.Loopback)
continue;
// 获取网络接口的IP属性
IPInterfaceProperties properties = ni.GetIPProperties();
// 遍历所有单播IP地址
foreach (UnicastIPAddressInformation ipaddr in properties.UnicastAddresses)
{
// 检查是否是IPv4地址
if (ipaddr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ip4 = ipaddr.Address.ToString();
break;
// 如果需要,也可以打印子网掩码
/* if (ipaddr.IPv4Mask != null)
{
Console.WriteLine($"子网掩码: {ipaddr.IPv4Mask}");
}*/
}
}
}
}
catch (Exception)
{
ip4 = "Error Ipv4";
}
return ip4;
}
// 通过网络接口获取本机Mac地址
private static string getMac()
{
string mac = "mac";
try
{
// 获取本机所有网络接口
NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in networkInterfaces)
{
// 忽略没有运行或没有IP配置的网络接口
if (ni.OperationalStatus != OperationalStatus.Up || ni.NetworkInterfaceType == NetworkInterfaceType.Loopback)
continue;
mac = ni.GetPhysicalAddress().ToString();
mac = StringAssistant.insertCharsWithStep(mac, 2, "-");
}
}
catch (Exception)
{
mac = "Error Macaddress";
}
return mac;
}
}
}