简体   繁体   中英

Converting IP address to host name via DNS.GetHostEntry

I am trying to get the hostname by passing in the ip address. 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.

Not all IP's are setup properly with a reverse DNS entry. These IP's are typically end consumers on lazy ISP's who don't provide PTR records for their clients. 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.

I'm using Dns.GetHostByAddress , even though it complains about being depreciated. (VS2010 targeting 3.5)

Dns.GetHostEntry seems to throw an exception if a the target host is not reachable even if DNS knows the hostname. There doesn't seem to be any .NET way around this except for using depreciated methods. :\

(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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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