gpt4 book ai didi

c# - 解析窗口 'ipconfig/all' 输出

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:00 24 4
gpt4 key购买 nike

我在使用正则表达式解析“ipconfig/all”的输出时遇到了一些麻烦。目前我正在使用 RegexBuddy 进行测试,但我想在 C#.NET 中使用正则表达式。

我的输出是:

Ethernet adapter Yes:

Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : MAC Bridge Miniport
Physical Address. . . . . . . . . : 02-1F-29-00-85-C9
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::f980:c9c3:a574:37a%24(Preferred)
Link-local IPv6 Address . . . . . : fe80::f980:c9c3:a574:37a7%24(Preferred)
Link-local IPv6 Address . . . . . : fe80::f980:c9c3:a574:37a8%24(Preferred)
IPv4 Address. . . . . . . . . . . : 10.0.0.1(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.0.0
IPv4 Address. . . . . . . . . . . : 172.16.0.1(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 172.16.0.254
DHCPv6 IAID . . . . . . . . . . . : 520228888
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-17-1C-CC-CF-00-1F-29-00-85-C9
DNS Servers . . . . . . . . . . . : 192.162.100.15
192.162.100.16
NetBIOS over Tcpip. . . . . . . . : Enabled

到目前为止我写的正则表达式是:

([ -~]+):.+(?:Description\s)(?:\.|\s)+:\s([ -~]+).+(?:Physical Address)(?:\.|\s)+:\s([ -~]+).+(?:DHCP Enabled)(?:\.|\s)+:\s([ -~]+).+(?:(?:Link-local IPv6 Address)(?:\.|\s)+:\s([ -~]+).+Preferred.+)+

问题是我想将所有有用的字段作为组捕获,以便在 C# 中轻松获取它们,但出于某种原因 - 当我捕获多个“链路本地 IPv6 地址”字段时,它停止工作了。

我会很感激任何帮助,谢谢。

编辑:另一个问题是我从远程机器接收 ipconfig 数据(那里有一个我无法控制的非托管程序)——因此我不能使用 WMI 或类似的东西以另一种方式获取 ipconfig 信息。

最佳答案

but I want to use the regex in C#.NET.

为什么使用正则表达式?相信我,您不想使用正则表达式。一位智者曾经说过:

Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems.

现在让我陈述您的 2 个问题:

  • 使用 ipconfig 检索有关 TCP/IP 配置的信息
  • 使用正则表达式解析此工具的输出

实际上,您可以直接使用 WMI 检索此信息,从而解决您原来的问题,再也不用考虑使用正则表达式了:

using (var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"))
using (var instances = mc.GetInstances())
{
foreach (ManagementObject instance in instances)
{
if (!(bool)instance["ipEnabled"])
{
continue;
}

Console.WriteLine("{0}, {1}, {2}", instance["Caption"], instance["ServiceName"], instance["MACAddress"]);

string[] ipAddresses = (string[])instance["IPAddress"];
string[] subnets = (string[])instance["IPSubnet"];
string[] gateways = (string[])instance["DefaultIPGateway"];
string domains = (string)instance["DNSDomain"];
string description = (string)instance["Description"];
bool dhcp = (bool)instance["DHCPEnabled"];
string[] dnses = (string[])instance["DNSServerSearchOrder"];
}
}

除此之外,您还可以使用 Mgmtclassgen.exe 为那些 WMI 类创建强类型包装器使您的代码更加安全的实用程序,您将能够摆脱魔法字符串。

关于c# - 解析窗口 'ipconfig/all' 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184495/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com