【获取IP】
一:适用于单网卡情形
string hostInfo = Dns.GetHostName();
//IP地址
//System.Net.IPAddress[] addressList = Dns.GetHostByName(hostInfo).AddressList;这个过时
System.Net.IPAddress[] addressList = Dns.GetHostEntry(hostInfo).AddressList;
ip = addressList[0].ToString();
二:适用于多网卡情形
foreach (NetworkInterface netInt in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties property = netInt.GetIPProperties();
foreach (UnicastIPAddressInformation ip in property.UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
ipaddr = ip.Address.ToString();
}
}
}
3.
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
if ((bool)mo["IPEnabled"] == true)
{
if (mo["IPAddress"] != null)
strIP = ((string[])mo["IPAddress"])[0];
}
else
{
strIP = "0.0.0.0";
}
【获取MAC】
1.
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
mac = mo["MacAddress"].ToString();
break;
}
}
2. NetworkInformation
foreach (NetworkInterface netInt in NetworkInterface.GetAllNetworkInterfaces()) {
netmac = netInt.GetPhysicalAddress().ToString();
}