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

C#中if语句失效,跨子网解析主机名报错求助

Fixing the Unresponsive If Statement for Cross-Subnet DNS Resolution Issues

Alright, let's break down why your if statement isn't working and fix that "No Host Found" error when resolving hostnames across subnets.

The Core Problem

The issue here is that Dns.GetHostEntry() doesn’t return a null or invalid value when it fails to resolve an IP (like across subnets) — it throws a SocketException (specifically error code 11001, which maps to "No such host is known"). Your if statement never gets a chance to run because the exception is thrown before reaching that logic.

How to Fix It

Instead of relying on an if check, you need to wrap the DNS resolution code in a try-catch block to handle the exception explicitly. Here's how to adjust your code:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string targetIp = "192.168.1.100"; // Replace with your target IP
        string hostName = "Unknown Host";

        try
        {
            // Attempt to resolve the IP to a hostname
            IPHostEntry hostEntry = Dns.GetHostEntry(targetIp);
            
            // If we reach this line, resolution succeeded
            if (!string.IsNullOrEmpty(hostEntry.HostName))
            {
                hostName = hostEntry.HostName;
                // Add your logic for successful resolution here
            }
        }
        catch (SocketException ex)
        {
            // Check if the exception is specifically "No Host Found"
            if (ex.ErrorCode == 11001)
            {
                // Handle cross-subnet or unreachable host scenario
                hostName = "Host unreachable (cross-subnet)";
                // Add your fallback logic here
            }
            else
            {
                // Re-throw other Socket exceptions if you need to handle them elsewhere
                throw;
            }
        }

        // Use the resolved or fallback hostname
        // Example: Label1.Text = hostName;
    }
}

Bonus: Prevent Unnecessary Resolution Attempts

If you want to avoid even trying to resolve non-local IPs (since you know they'll fail), you can add a pre-check to verify if the IP is within your local subnet first. Here's a helper method to do that:

private bool IsLocalSubnetIp(string ipAddress)
{
    if (!IPAddress.TryParse(ipAddress, out IPAddress ip))
        return false;

    byte[] ipBytes = ip.GetAddressBytes();
    
    // Check for private IP ranges (common local subnets)
    return (ipBytes[0] == 10) || 
           (ipBytes[0] == 172 && ipBytes[1] >= 16 && ipBytes[1] <= 31) || 
           (ipBytes[0] == 192 && ipBytes[1] == 168);
}

Then use it in your code:

if (IsLocalSubnetIp(targetIp))
{
    // Only attempt resolution for local subnet IPs
    try
    {
        IPHostEntry hostEntry = Dns.GetHostEntry(targetIp);
        hostName = hostEntry.HostName;
    }
    catch (SocketException ex) when (ex.ErrorCode == 11001)
    {
        hostName = "Local host not found";
    }
}
else
{
    // Skip resolution for non-local IPs
    hostName = "Non-local IP (no resolution attempted)";
}

This way, you avoid unnecessary exceptions and make your code more efficient.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:31:40