获得网卡和Ip地址
2015-12-13 10:02:14 访问(3872) 赞(0) 踩(0)
相关下载:SlowX.GetPhyAddressApp[code] SlowX.GetPhyAddressApp[release] 百度云
-

-
#region 获取主板物理网卡地址
/// <summary>
/// 获取主板物理网卡地址
/// </summary>
/// <returns></returns>
public string GetNetworkAddress(bool isValid)
{
try
{
StringBuilder theResult = new StringBuilder();
bool isFirst = true;
string strMac = null;
NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in fNetworkInterfaces)
{
strMac = null;
if (isValid)
{
string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
//int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI")
{
if (adapter.GetPhysicalAddress() != null)
{
strMac = adapter.GetPhysicalAddress().ToString();
}
}
//else
//{
// if (fMediaSubType == 2)
// {
// //无线网卡
// }
// if (fMediaSubType == 1)
// {
// //虚拟网卡
// }
//}
}
}
else
{
if (adapter.GetPhysicalAddress() != null)
{
strMac = adapter.GetPhysicalAddress().ToString();
}
}
if (strMac != null && strMac.Length > 0)
{
if (isFirst)
{
isFirst = false;
}
else
{
theResult.Append("|");
}
theResult.Append(strMac);
}
}
return theResult.ToString();
}
catch
{
return "";
}
}
#endregion
#region 获得IP地址
/// <summary>
/// 获得IP地址
/// </summary>
/// <returns></returns>
public static string GetHostName()
{
return Dns.GetHostName();
}
/// <summary>
/// 获得IP地址
/// </summary>
/// <returns></returns>
public static IPAddress[] GetLocalIP()
{
string name = Dns.GetHostName();
IPHostEntry me = Dns.GetHostEntry(name);
return me.AddressList;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IPAddress GetFirstIP()
{
IPAddress[] ips = GetLocalIP();
foreach (IPAddress ip in ips)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
continue;
return ip;
}
return ips != null && ips.Length > 0 ? ips[0] : new IPAddress(0x0);
}
/// <summary>
/// 获得IP地址
/// </summary>
/// <returns></returns>
public string GetIPAddress()
{
try
{
string hostName = Dns.GetHostName();
if (hostName == null || hostName.Length == 0)
return "";
IPHostEntry me = Dns.GetHostEntry(hostName);
if (me == null)
return "";
IPAddress[] ips = me.AddressList;
if (ips == null)
return "";
StringBuilder theResult = new StringBuilder();
bool isFirst = true;
foreach (IPAddress ip in ips)
{
if (ip.AddressFamily !=
System.Net.Sockets.AddressFamily.InterNetwork)
continue;
try
{
if (isFirst)
isFirst = false;
else
theResult.Append("|");
theResult.Append(ip.ToString());
}
catch
{
}
}
return theResult.ToString();
}
catch
{
return "";
}
}
#endregion 获得IP地址
标签:
获得网卡和Ip地址 


上一条:
下一条:
相关评论
发表评论