当前位置 : 主页 > 网络编程 > net编程 >

获取mac地址和IP地址方式

来源:互联网 收集:自由互联 发布时间:2023-09-07
第一种 public class OperateMAC { public static string GetMacByWMI() { string MacAddr = null; //ManagementObjectSearcher Query = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration"); //ManagementObjectCollection


第一种

public class OperateMAC
{
public static string GetMacByWMI()
{
string MacAddr = null;
//ManagementObjectSearcher Query = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration");
//ManagementObjectCollection QueryCollection = Query.Get();
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (mo["IPEnabled"].ToString() == "True")
MacAddr = mo["MacAddress"].ToString();
}
return MacAddr;
} public static string GetIpByWMI()
{
string IpAddr = string.Empty;
System.NET.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
for (int i = 0; i < addressList.Length; i++)
{
IpAddr = addressList[i].ToString();
}
return IpAddr;
}
}

第二种

private string GetMacAddress()
{
List<string> macs = new List<string>();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
macs.Add(ni.GetPhysicalAddress().ToString());
}
return macs.FirstOrDefault();
}
private string GetIPAddress()
{
string strHostName = Dns.GetHostName(); //得到本机的主机名
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); //取得本机IP
if (ipEntry.AddressList.Length == 0) return null;
IPAddress ipAddress = ipEntry.AddressList.FirstOrDefault(item => item.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
if (ipAddress == null) ipAddress = ipEntry.AddressList[0];
return ipAddress.ToString();
}

龙腾一族至尊龙骑

上一篇:C# WinForm窗体界面设置
下一篇:没有了
网友评论