简体   繁体   English

通过 DNS.GetHostEntry 将 IP 地址转换为主机名

[英]Converting IP address to host name via DNS.GetHostEntry

I am trying to get the hostname by passing in the ip address.我试图通过传入 ip 地址来获取主机名。 I use the following code.我使用以下代码。

System.Net.Dns.GetHostEntry("192.168.x.x").HostName

For some host the above code is returning correctly the hostname, but for few other host it throws an exception 'No Such host found'.对于某些主机,上述代码正确返回主机名,但对于少数其他主机,它会引发异常“未找到此类主机”。

Could any one tell me why is this happening for some hosts?谁能告诉我为什么某些主机会发生这种情况?

I used the above code in an asp.net mvc application.我在 asp.net mvc 应用程序中使用了上述代码。

Not all IP's are setup properly with a reverse DNS entry.并非所有 IP 都使用反向 DNS 条目正确设置。 These IP's are typically end consumers on lazy ISP's who don't provide PTR records for their clients.这些 IP 通常是不为其客户提供PTR记录的惰性 ISP 的最终消费者。 If there's no reverse entry, you can bet there's no forward entry either.如果没有反向进入,您可以打赌也没有正向进入。 As such, these hosts have no hostname at all , hence the exception.因此,这些主机根本没有主机名,因此例外。 You'll need to catch this exception for these hosts and use something else such as their IP as an identifier.您需要为这些主机捕获此异常并使用其他内容(例如其 IP)作为标识符。

I'm using Dns.GetHostByAddress , even though it complains about being depreciated.我正在使用Dns.GetHostByAddress ,即使它抱怨被贬值。 (VS2010 targeting 3.5) (VS2010 针对 3.5)

Dns.GetHostEntry seems to throw an exception if a the target host is not reachable even if DNS knows the hostname.如果目标主机不可访问,即使 DNS 知道主机名, Dns.GetHostEntry似乎也会引发异常。 There doesn't seem to be any .NET way around this except for using depreciated methods.除了使用折旧的方法外,似乎没有任何 .NET 解决方法。 :\ :\

(edit: though the above answer is also true - some machines just don't have hostnames. my answer is just if you know it should have a hostname but GetHostEntry doesn't work) (编辑:虽然上面的答案也是正确的 - 有些机器只是没有主机名。我的答案是如果你知道它应该有一个主机名但GetHostEntry不起作用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM