基于WMI获取本机真实网卡物理地址和IP地址
using System;
using System.Collections.Generic;
using System.Management;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions; namespace Splash.Util
{
public class NetworkAdapterInformation
{
public String PNPDeviceID; // 设备ID
public UInt32 Index; // 在系统注册表中的索引号
public String ProductName; // 产品名称
public String ServiceName; // 服务名称 public String MACAddress; // 网卡当前物理地址
public String PermanentAddress; // 网卡原生物理地址 public String IPv4Address; // IP 地址
public String IPv4Subnet; // 子网掩码
public String IPv4Gateway; // 默认网关
public Boolean IPEnabled; // 有效状态
} /// <summary>
/// 基于WMI获取本机真实网卡信息
/// </summary>
public static class NetworkAdapter
{
/// <summary>
/// 获取本机真实网卡信息,包括物理地址和IP地址
/// </summary>
/// <param name="isIncludeUsb">是否包含USB网卡,默认为不包含</param>
/// <returns>本机真实网卡信息</returns>
public static NetworkAdapterInformation[] GetNetworkAdapterInformation(Boolean isIncludeUsb = false)
{ // IPv4正则表达式
const String IPv4RegularExpression = "^(?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))$"; // 注意:只获取已连接的网卡
String NetworkAdapterQueryString;
if (isIncludeUsb)
NetworkAdapterQueryString = "SELECT * FROM Win32_NetworkAdapter WHERE (NetConnectionStatus = 2) AND (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE 'ROOT%'))";
else
NetworkAdapterQueryString = "SELECT * FROM Win32_NetworkAdapter WHERE (NetConnectionStatus = 2) AND (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE 'ROOT%')) AND (NOT (PNPDeviceID LIKE 'USB%'))"; ManagementObjectCollection NetworkAdapterQueryCollection = new ManagementObjectSearcher(NetworkAdapterQueryString).Get();
if (NetworkAdapterQueryCollection == null) return null; List<NetworkAdapterInformation> NetworkAdapterInformationCollection = new List<NetworkAdapterInformation>(NetworkAdapterQueryCollection.Count);
foreach (ManagementObject mo in NetworkAdapterQueryCollection)
{
NetworkAdapterInformation NetworkAdapterItem = new NetworkAdapterInformation();
NetworkAdapterItem.PNPDeviceID = mo["PNPDeviceID"] as String;
NetworkAdapterItem.Index = (UInt32)mo["Index"];
NetworkAdapterItem.ProductName = mo["ProductName"] as String;
NetworkAdapterItem.ServiceName = mo["ServiceName"] as String;
NetworkAdapterItem.MACAddress = mo["MACAddress"] as String; // 网卡当前物理地址 // 网卡原生物理地址
NetworkAdapterItem.PermanentAddress = GetNetworkAdapterPermanentAddress(NetworkAdapterItem.PNPDeviceID); // 获取网卡配置信息
String ConfigurationQueryString = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = " + NetworkAdapterItem.Index.ToString();
ManagementObjectCollection ConfigurationQueryCollection = new ManagementObjectSearcher(ConfigurationQueryString).Get();
if (ConfigurationQueryCollection == null) continue; foreach (ManagementObject nacmo in ConfigurationQueryCollection)
{
String[] IPCollection = nacmo["IPAddress"] as String[]; // IP地址
if (IPCollection != null)
{
foreach (String adress in IPCollection)
{
Match match = Regex.Match(adress, IPv4RegularExpression);
if (match.Success) { NetworkAdapterItem.IPv4Address = adress; break; }
}
} IPCollection = nacmo["IPSubnet"] as String[]; // 子网掩码
if (IPCollection != null)
{
foreach (String address in IPCollection)
{
Match match = Regex.Match(address, IPv4RegularExpression);
if (match.Success) { NetworkAdapterItem.IPv4Subnet = address; break; }
}
} IPCollection = nacmo["DefaultIPGateway"] as String[]; // 默认网关
if (IPCollection != null)
{
foreach (String address in IPCollection)
{
Match match = Regex.Match(address, IPv4RegularExpression);
if (match.Success) { NetworkAdapterItem.IPv4Gateway = address; break; }
}
} NetworkAdapterItem.IPEnabled = (Boolean)nacmo["IPEnabled"];
} NetworkAdapterInformationCollection.Add(NetworkAdapterItem);
} if (NetworkAdapterInformationCollection.Count > ) return NetworkAdapterInformationCollection.ToArray(); else return null;
} /// <summary>
/// 获取网卡原生物理地址
/// </summary>
/// <param name="PNPDeviceID">设备ID</param>
/// <returns>网卡原生物理地址</returns>
public static String GetNetworkAdapterPermanentAddress(String PNPDeviceID)
{
const UInt32 FILE_SHARE_READ = 0x00000001;
const UInt32 FILE_SHARE_WRITE = 0x00000002;
const UInt32 OPEN_EXISTING = ;
const UInt32 OID_802_3_PERMANENT_ADDRESS = 0x01010101;
const UInt32 IOCTL_NDIS_QUERY_GLOBAL_STATS = 0x00170002;
IntPtr INVALID_HANDLE_VALUE = new IntPtr(-); // 生成设备路径名
String DevicePath = "\\\\.\\" + PNPDeviceID.Replace('\\', '#') + "#{ad498944-762f-11d0-8dcb-00c04fc3358c}"; // 获取设备句柄
IntPtr hDeviceFile = CreateFile(DevicePath, , FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, , IntPtr.Zero);
if (hDeviceFile != INVALID_HANDLE_VALUE)
{
Byte[] ucData = new Byte[];
Int32 nBytesReturned; // 获取原生MAC地址
UInt32 dwOID = OID_802_3_PERMANENT_ADDRESS;
Boolean isOK = DeviceIoControl(hDeviceFile, IOCTL_NDIS_QUERY_GLOBAL_STATS, ref dwOID, Marshal.SizeOf(dwOID), ucData, ucData.Length, out nBytesReturned, IntPtr.Zero);
CloseHandle(hDeviceFile);
if (isOK)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(nBytesReturned * );
foreach (Byte b in ucData)
{
sb.Append(b.ToString("X2"));
sb.Append(':');
}
return sb.ToString(, nBytesReturned * - );
}
} return null;
} [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CreateFile(
String lpFileName,
UInt32 dwDesiredAccess,
UInt32 dwShareMode,
IntPtr lpSecurityAttributes,
UInt32 dwCreationDisposition,
UInt32 dwFlagsAndAttributes,
IntPtr hTemplateFile
); [DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern Boolean DeviceIoControl(
IntPtr hDevice,
UInt32 dwIoControlCode,
ref UInt32 lpInBuffer,
Int32 nInBufferSize,
Byte[] lpOutBuffer,
Int32 nOutBufferSize,
out Int32 nBytesReturned,
IntPtr lpOverlapped
);
}
}
using
System;
using
System.Collections.Generic;
using
System.Management;
using
System.Runtime.InteropServices;
using
System.Text.RegularExpressions;
namespace
Splash.Util
{
public
class
NetworkAdapterInformation
{
public
String PNPDeviceID;
// 设备ID
public
UInt32 Index;
// 在系统注册表中的索引号
public
String ProductName;
// 产品名称
public
String ServiceName;
// 服务名称
public
String MACAddress;
// 网卡当前物理地址
public
String PermanentAddress;
// 网卡原生物理地址
public
String IPv4Address;
// IP 地址
public
String IPv4Subnet;
// 子网掩码
public
String IPv4Gateway;
// 默认网关
public
Boolean IPEnabled;
// 有效状态
}
/// <summary>
/// 基于WMI获取本机真实网卡信息
/// </summary>
public
static
class
NetworkAdapter
{
/// <summary>
/// 获取本机真实网卡信息,包括物理地址和IP地址
/// </summary>
/// <param name="isIncludeUsb">是否包含USB网卡,默认为不包含</param>
/// <returns>本机真实网卡信息</returns>
public
static
NetworkAdapterInformation[] GetNetworkAdapterInformation(Boolean isIncludeUsb =
false
)
{
// IPv4正则表达式
const
String IPv4RegularExpression =
"^(?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))$"
;
// 注意:只获取已连接的网卡
String NetworkAdapterQueryString;
if
(isIncludeUsb)
NetworkAdapterQueryString =
"SELECT * FROM Win32_NetworkAdapter WHERE (NetConnectionStatus = 2) AND (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE 'ROOT%'))"
;
else
NetworkAdapterQueryString =
"SELECT * FROM Win32_NetworkAdapter WHERE (NetConnectionStatus = 2) AND (MACAddress IS NOT NULL) AND (NOT (PNPDeviceID LIKE 'ROOT%')) AND (NOT (PNPDeviceID LIKE 'USB%'))"
;
ManagementObjectCollection NetworkAdapterQueryCollection =
new
ManagementObjectSearcher(NetworkAdapterQueryString).Get();
if
(NetworkAdapterQueryCollection ==
null
)
return
null
;
List<NetworkAdapterInformation> NetworkAdapterInformationCollection =
new
List<NetworkAdapterInformation>(NetworkAdapterQueryCollection.Count);
foreach
(ManagementObject mo
in
NetworkAdapterQueryCollection)
{
NetworkAdapterInformation NetworkAdapterItem =
new
NetworkAdapterInformation();
NetworkAdapterItem.PNPDeviceID = mo[
"PNPDeviceID"
]
as
String;
NetworkAdapterItem.Index = (UInt32)mo[
"Index"
];
NetworkAdapterItem.ProductName = mo[
"ProductName"
]
as
String;
NetworkAdapterItem.ServiceName = mo[
"ServiceName"
]
as
String;
NetworkAdapterItem.MACAddress = mo[
"MACAddress"
]
as
String;
// 网卡当前物理地址
// 网卡原生物理地址
NetworkAdapterItem.PermanentAddress = GetNetworkAdapterPermanentAddress(NetworkAdapterItem.PNPDeviceID);
// 获取网卡配置信息
String ConfigurationQueryString =
"SELECT * FROM Win32_NetworkAdapterConfiguration WHERE Index = "
+ NetworkAdapterItem.Index.ToString();
ManagementObjectCollection ConfigurationQueryCollection =
new
ManagementObjectSearcher(ConfigurationQueryString).Get();
if
(ConfigurationQueryCollection ==
null
)
continue
;
foreach
(ManagementObject nacmo
in
ConfigurationQueryCollection)
{
String[] IPCollection = nacmo[
"IPAddress"
]
as
String[];
// IP地址
if
(IPCollection !=
null
)
{
foreach
(String adress
in
IPCollection)
{
Match match = Regex.Match(adress, IPv4RegularExpression);
if
(match.Success) { NetworkAdapterItem.IPv4Address = adress;
break
; }
}
}
IPCollection = nacmo[
"IPSubnet"
]
as
String[];
// 子网掩码
if
(IPCollection !=
null
)
{
foreach
(String address
in
IPCollection)
{
Match match = Regex.Match(address, IPv4RegularExpression);
if
(match.Success) { NetworkAdapterItem.IPv4Subnet = address;
break
; }
}
}
IPCollection = nacmo[
"DefaultIPGateway"
]
as
String[];
// 默认网关
if
(IPCollection !=
null
)
{
foreach
(String address
in
IPCollection)
{
Match match = Regex.Match(address, IPv4RegularExpression);
if
(match.Success) { NetworkAdapterItem.IPv4Gateway = address;
break
; }
}
}
NetworkAdapterItem.IPEnabled = (Boolean)nacmo[
"IPEnabled"
];
}
NetworkAdapterInformationCollection.Add(NetworkAdapterItem);
}
if
(NetworkAdapterInformationCollection.Count > 0)
return
NetworkAdapterInformationCollection.ToArray();
else
return
null
;
}
/// <summary>
/// 获取网卡原生物理地址
/// </summary>
/// <param name="PNPDeviceID">设备ID</param>
/// <returns>网卡原生物理地址</returns>
public
static
String GetNetworkAdapterPermanentAddress(String PNPDeviceID)
{
const
UInt32 FILE_SHARE_READ = 0x00000001;
const
UInt32 FILE_SHARE_WRITE = 0x00000002;
const
UInt32 OPEN_EXISTING = 3;
const
UInt32 OID_802_3_PERMANENT_ADDRESS = 0x01010101;
const
UInt32 IOCTL_NDIS_QUERY_GLOBAL_STATS = 0x00170002;
IntPtr INVALID_HANDLE_VALUE =
new
IntPtr(-1);
// 生成设备路径名
String DevicePath =
"\\\\.\\"
+ PNPDeviceID.Replace(
'\\'
,
'#'
) +
"#{ad498944-762f-11d0-8dcb-00c04fc3358c}"
;
// 获取设备句柄
IntPtr hDeviceFile = CreateFile(DevicePath, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if
(hDeviceFile != INVALID_HANDLE_VALUE)
{
Byte[] ucData =
new
Byte[8];
Int32 nBytesReturned;
// 获取原生MAC地址
UInt32 dwOID = OID_802_3_PERMANENT_ADDRESS;
Boolean isOK = DeviceIoControl(hDeviceFile, IOCTL_NDIS_QUERY_GLOBAL_STATS,
ref
dwOID, Marshal.SizeOf(dwOID), ucData, ucData.Length,
out
nBytesReturned, IntPtr.Zero);
CloseHandle(hDeviceFile);
if
(isOK)
{
System.Text.StringBuilder sb =
new
System.Text.StringBuilder(nBytesReturned * 3);
foreach
(Byte b
in
ucData)
{
sb.Append(b.ToString(
"X2"
));
sb.Append(
':'
);
}
return
sb.ToString(0, nBytesReturned * 3 - 1);
}
}
return
null
;
}
[DllImport(
"kernel32.dll"
, CharSet = CharSet.Auto, SetLastError =
true
)]
public
static
extern
IntPtr CreateFile(
String lpFileName,
UInt32 dwDesiredAccess,
UInt32 dwShareMode,
IntPtr lpSecurityAttributes,
UInt32 dwCreationDisposition,
UInt32 dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[DllImport(
"kernel32.dll"
, SetLastError =
true
)]
[
return
: MarshalAs(UnmanagedType.Bool)]
public
static
extern
Boolean CloseHandle(IntPtr hObject);
[DllImport(
"kernel32.dll"
, CharSet = CharSet.Ansi, SetLastError =
true
)]
[
return
: MarshalAs(UnmanagedType.Bool)]
internal
static
extern
Boolean DeviceIoControl(
IntPtr hDevice,
UInt32 dwIoControlCode,
ref
UInt32 lpInBuffer,
Int32 nInBufferSize,
Byte[] lpOutBuffer,
Int32 nOutBufferSize,
out
Int32 nBytesReturned,
IntPtr lpOverlapped
);
}
}
基于WMI获取本机真实网卡物理地址和IP地址的更多相关文章
- js获取本机的外网/广域网ip地址
完整源代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...
- 用 shell 获取本机的网卡名称
用 shell 获取本机的网卡名称 # 用 shell 获取本机的网卡名称 ls /sys/class/net # 或者 ifconfig | grep "Link" | awk ...
- GetAdaptersInfo获取网卡配置和Ip地址信息
一台机器上可能不只有一个网卡,但每一个网卡只有一个MAC地址,而每一个网卡可能配置有多个IP地址:如平常的笔记本电脑中,就会有无线网卡和有线网卡(网线接口)两种:因此,如果要获得本机所有网卡的IP和M ...
- ubuntu下仅仅获取网卡一的ip地址 && shell中字符串拼接
问题描述: ubuntu下仅仅获取网卡一的ip地址 问题背景: eth0,eth1,eth2……代表网卡一,网卡二,网卡三…… lo代表127.0.0.1,即localhost | 问题描述: 已知字 ...
- 【liunx】使用xshell连接虚拟机上的CentOS 7,使用xhell连接本地虚拟机上的Ubuntu, 获取本地虚拟机中CentOS 7的IP地址,获取本地虚拟机中Ubuntu 的IP地址,Ubuntu开启22端口
注意,如果想用xshell去连接本地虚拟机中的linux系统,需要本地虚拟机中的系统是启动的才能连接!!!!! ============================================ ...
- Java 网络编程(1):使用 NetworkInterface 获得本机在局域网内的 IP 地址
原文地址:https://segmentfault.com/a/1190000007462741 1.问题提出 在使用 Java 开发网络程序时,有时候我们需要知道本机在局域网中的 IP 地址.很常见 ...
- 烂泥:更换ESXI5.0管理网卡及管理IP地址
本文由秀依林枫提供友情赞助,首发于烂泥行天下. 公司的服务器基本上都是在IDC机房里面的,为了更有效的利用服务器性能.所以有几台服务器,安装的是ESXI5.0做成虚拟化. 注意目前这些服务器都是双网卡 ...
- Ubuntu 为网卡配置静态IP地址
为网卡配置静态IP地址编辑文件/etc/network/interfaces:sudo vi /etc/network/interfaces并用下面的行来替换有关eth0的行:# The primar ...
- vmware虚拟机下linux centos6.6只有lo,没有eth0网卡、随机分配ip地址,固定ip地址等问题
这个问题卡了我一天多的时间,百度上搜出来的问题五花八门,反而把我给搞糊涂了.最后总算是实践成功了,记录一下配置的过程. 配置网卡和随机分配ip地址 我安装的是basic server版本,用的是NAT ...
随机推荐
- 用js取1-100的随机数
function sum (m,n){ var num = Math.floor(Math.random()*(m - n) + n); alert(num) } sum(1,100): 万能 公式, ...
- Java实现哈夫曼编码和解码
最近无意中想到关于api返回值加密的问题,譬如我们的api需要返回一些比较敏感或者重要不想让截获者得到的信息,像如果是做原创图文的,文章明文返回的话则有可能被抓包者窃取. 关于请求时加密的方式比较多, ...
- Python: PS 图像调整--明度调整
本文用 Python 实现 PS 图像调整中的明度调整: 我们知道,一般的非线性RGB亮度调整只是在原有R.G.B值基础上增加和减少一定量来实现的,而PS的明度调整原理还得从前面那个公式上去找.我们将 ...
- Eclipse Error: The refactoring does not change any source code
最近在做android项目的过程中遇到这样一个问题,新增一个activity的时候添加不成,eclipse提示The refactoring does not change any source co ...
- linux-锁屏时间设置
系统:ubuntu16.04 操作步骤 设置setting -> System Settings -> Brightness&lock, 在界面中选择想要的设置即可: 参考 1.百 ...
- 发布网站的时候发现360极速浏览器ie7内核不兼容样式的问题
引言: 在Web应用的开发过程中,发现若干页面在360的浏览器上显示不正常,而在其他的浏览器上,皆为正常状态,问题出在哪里呢? 问题的提出: Web页面在360的浏览器上,显示不正确. 但是在Fir ...
- java面试题12
1. jsp与servlet的区分? 答:Servlet和JSP都是基于java语言上的动态网页技术,Servlet程序其实就是java程序,只不过它所使用的类库为JAVA Servlet API, ...
- 定义一组抽象的 Awaiter 的实现接口,你下次写自己的 await 可等待对象时将更加方便
我在几篇文章中都说到了在 .NET 中自己实现 Awaiter 情况.async / await 写异步代码用起来真的很爽,就像写同步一样.然而实现 Awaiter 没有现成的接口,它需要你按照编译器 ...
- POJ3276(遍历+区间修改)
http://poj.org/problem?id=3276 题意:n(n<=5000)头牛站成线,有朝前有朝后的的,然后每次可以选择大小为k的区间里的牛全部转向,会有一个最小操作m次使得它们全 ...
- 2、let 和 const 命令
let 命令 块级作用域 const 命令 顶层对象的属性 global 对象 let 命令 基本用法 ES6 新增了let命令,用来声明变量.它的用法类似于var,但是所声明的变量,只在let命令所 ...