基于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 ...
随机推荐
- Python API快餐教程(1) - 字符串查找API
字符串处理相关API 字符串是7种序列类型中的一种. 除了序列的操作函数,比如len()来求字符串长度之外,Python还为字符串提供丰富到可以写个编辑器的API. 查找类API 首先,下面的查找AP ...
- android系列9.LinearLayout 学习2
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...
- 8.1 服务器开发 API 函数封装,select 优化服务器和客户端
#include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <ne ...
- David Silver 强化学习原理 (中文版 链接)
教程的在线视频链接: http://www.bilibili.com/video/av9831889/ 全部视频链接: https://space.bilibili.com/74997410/vide ...
- .NET/C# 项目如何优雅地设置条件编译符号?
条件编译符号指的是 Conditional Compilation Symbols.你可以在 Visual Studio 的项目属性中设置,也可以直接在项目文件中写入 DefineConstants ...
- ACCESS不可识别的数据库格式!
在Access07之前的数据库后缀名均为*.mdb 而连接字符串写成Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\myFolder\*.mdb ;Pe ...
- HDU 4681 string 求最长公共子序列的简单DP+暴力枚举
先预处理,用求最长公共子序列的DP顺着处理一遍,再逆着处理一遍. 再预处理串a和b中包含串c的子序列,当然,为了使这子序列尽可能短,会以c 串的第一个字符开始 ,c 串的最后一个字符结束 将这些起始位 ...
- BZOJ2460,LG4570 [BJWC2011]元素
题意 相传,在远古时期,位于西方大陆的 Magic Land 上,人们已经掌握了用魔法矿石炼制法杖的技术.那时人们就认识到,一个法杖的法力取决于使用的矿石. 一般地,矿石越多则法力越强,但物极必反:有 ...
- google play apk 下载
https://apps.evozi.com/apk-downloader/?id=com.sgiggle.production
- mysql学习--mysql必知必会
上图为数据库操作分类: 下面的操作參考(mysql必知必会) 创建数据库 运行脚本建表: mysql> create database mytest; Query OK, 1 row ...