You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#获取特定网段(10.开头)的系统IPv4地址?

筛选以“10.”开头的IPv4地址解决方案

基于原代码的快速修改

你可以直接在原筛选逻辑中增加IP前缀判断,锁定10.网段的地址:

string ipAddress = Dns.GetHostEntry(Dns.GetHostName())
    .AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork 
                                    && ip.ToString().StartsWith("10."))
    ?.ToString();

if (!string.IsNullOrEmpty(ipAddress))
{
    System.Windows.Forms.MessageBox.Show(ipAddress);
}
else
{
    System.Windows.Forms.MessageBox.Show("未找到以10.开头的IPv4地址");
}

改动说明:

  • 新增ip.ToString().StartsWith("10.")条件,精准匹配目标网段
  • 用?.ToString()避免找不到IP时触发空引用异常
  • 增加空值判断,给用户明确的结果反馈

更可靠的网络接口枚举方案

如果Dns.GetHostEntry返回结果不全(比如未联网接口的IP不会被DNS解析到),可以直接枚举本地网络接口获取IP,这种方式更精准:

using System.Net.NetworkInformation;

string targetIp = null;
foreach (var networkInterface in NetworkInterface.GetAllNetworkInterfaces())
{
    // 跳过未启用的网络接口
    if (networkInterface.OperationalStatus != OperationalStatus.Up)
        continue;

    foreach (var unicastAddress in networkInterface.GetIPProperties().UnicastAddresses)
    {
        if (unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork
            && unicastAddress.Address.ToString().StartsWith("10."))
        {
            targetIp = unicastAddress.Address.ToString();
            break;
        }
    }
    if (targetIp != null)
        break;
}

if (targetIp != null)
{
    System.Windows.Forms.MessageBox.Show(targetIp);
}
else
{
    System.Windows.Forms.MessageBox.Show("未找到以10.开头的IPv4地址");
}

该方案会遍历所有启用状态的网络接口,逐一检查绑定的单播IPv4地址,确保不会遗漏符合条件的IP。

内容的提问来源于stack exchange,提问作者itsenaf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 12:45:43