C# Dns.GetHostEntry() - 异常:没有这样的主机已知

2024-05-01

From 文档 https://learn.microsoft.com/en-us/dotnet/api/system.net.dns.gethostentry?view=netframework-4.8 Dns.GetHostEntry() 将主机名或 IP 地址解析为 IPHostEntry 实例。谁能帮我理解为什么这个功能对某些外部IP地址不起作用(它对内部IP地址起作用)而ping命令正常工作?

我的代码是:

using System;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Please enter a host name or IP address");
                Console.WriteLine("Usage: ConsoleApplication1 8.8.8.8");
                return 1;
            }

            string addr = args[0];

            try
            {
                IPHostEntry host = Dns.GetHostEntry(addr);
                Console.WriteLine($"GetHostEntry({addr}) returns HostName: {host.HostName}");
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}", e);
            }

            return 0;
        }

    }
}

Output:

C:\Users\Administrator\Desktop>ping stackoverflow.com
    
Pinging stackoverflow.com [151.101.1.69] with 32 bytes of data:
Reply from 151.101.1.69: bytes=32 time=35ms TTL=57
Reply from 151.101.1.69: bytes=32 time=16ms TTL=57
Reply from 151.101.1.69: bytes=32 time=16ms TTL=57
Reply from 151.101.1.69: bytes=32 time=16ms TTL=57

Ping statistics for 151.101.1.69:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 16ms, Maximum = 35ms, Average = 20ms

C:\Users\Administrator\Desktop>ConsoleApplication1.exe 151.101.1.69
Exception: System.Net.Sockets.SocketException (0x80004005): No such host is known
   at System.Net.Dns.InternalGetHostByAddress(IPAddress address, Boolean includeIPv6)
   at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
   at ConsoleApplication1.Program.Main(String[] args)

C:\Users\Administrator\Desktop>ping 151.101.1.69

Pinging 151.101.1.69 with 32 bytes of data:
Reply from 151.101.1.69: bytes=32 time=27ms TTL=57
Reply from 151.101.1.69: bytes=32 time=16ms TTL=57
Reply from 151.101.1.69: bytes=32 time=16ms TTL=57
Reply from 151.101.1.69: bytes=32 time=17ms TTL=57

Ping statistics for 151.101.1.69:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 16ms, Maximum = 27ms, Average = 19ms

我找到了更改文件的解决方案

C:\Windows\System32\drivers\etc\hosts

添加行:

151.101.1.69 stackoverflow.com

此更改后有效

C:\Users\Administrator\Desktop>ConsoleApplication1.exe 151.101.1.69
GetHostEntry(151.101.1.69) returns HostName: stackoverflow.com

在我看来,更改主机文件并不是解决此问题的好方法。有谁知道更好的解决方案来解决这个问题?


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# Dns.GetHostEntry() - 异常:没有这样的主机已知 的相关文章

随机推荐