如何使用C#获取与ipconfig命令输出一致的本机IPv4地址
问题原因
你现有代码的问题在于Dns.GetHostEntry(Dns.GetHostName())返回的IPv4地址列表没有固定排序,且会包含所有未禁用的网卡(包括虚拟网卡、VPN网卡、WSL虚拟网卡等)的地址,直接取第一个结果自然会和ipconfig里优先展示的物理网卡活跃IP不一致。
方案1:直接调用ipconfig命令解析结果(100%和ipconfig输出一致)
这个方案直接执行系统的ipconfig命令提取输出内容,结果和你手动执行ipconfig的返回完全一致,最适配你的需求:
using System.Diagnostics; using System.Text.RegularExpressions; public static List<string> GetIpConfigIPv4Addresses() { List<string> ipv4List = new List<string>(); Process process = new Process(); process.StartInfo.FileName = "ipconfig"; process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; // 中文系统用GB2312编码,英文系统替换为Encoding.ASCII process.StartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding("GB2312"); process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); // 正则匹配IPv4地址,中文系统请把"IPv4 Address"改为"IPv4 地址" Regex regex = new Regex(@"IPv4 Address.*?:\s*(\d+\.\d+\.\d+\.\d+)"); MatchCollection matches = regex.Matches(output); foreach (Match match in matches) { if (match.Success) { ipv4List.Add(match.Groups[1].Value); } } return ipv4List; }
如果只需要ipconfig排序第一位的IP,直接取返回列表的第一个元素即可。
方案2:用NetworkInterface类遍历获取(无外部命令依赖,性能更高)
如果你不想调用系统命令,可以用.NET内置的网络接口类,按ipconfig的过滤逻辑筛选网卡后获取IPv4,结果和ipconfig输出一致:
using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; public static List<string> GetPhysicalIPv4Addresses() { List<string> ipv4List = new List<string>(); foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { // 过滤条件:物理网卡(以太网/WiFi)、已连接、非回环/虚拟隧道网卡 if ((ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet || ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) && ni.OperationalStatus == OperationalStatus.Up && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Tunnel) { foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { ipv4List.Add(ip.Address.ToString()); } } } } return ipv4List; }
注意事项
- 如果服务器有多网卡,可以自行增加过滤条件(比如匹配网卡名称、指定网关段)筛选你需要的目标IP
- IIS环境下运行时默认应用池权限就可以正常调用上述代码,不需要额外提权
内容的提问来源于stack exchange,提问作者Celty
相关产品推荐
相关产品推荐

