Question

Problem: there's an input field in an application where the user can enter either a host name or an IP address. I need to tell if the entered address corresponds to a real host.

I'm not talking about a simple regular expression check or an IPAddress.TryParse or Uri.CheckHostName. I don't have difficulty with checking a hostname: if it cannot be resolved to an IP address, then Dns.GetHostEntry will throw an exception. That's a piece of cake.

However. If I get an IP address input, then if I make a Dns.GetHostAddresses call it'll always succeed, even if I enter a stupid IP, like "1.1.1.1" ("1.1.1.1" is an IANA reserved IP address, our DNS server reports "non existent host/domain"). The Dns.GetHostAddresses immediately just spits back the IP I just passed in like everything would be all right whatsoever.

I cannot use the Dns.GetHostEntry either, because there are some IP addresses (like my virtual machines on the local network) which don't have any DNS host names associated with them, but they still have valid IP addresses, and Dns.GetHostEntry would throw exception to those (I guess it tries to resolve a hostname for them?).

I need a method call which actually tells me if it is a bogus IP or not, even if it looks like good IP address (by Uri.CheckHostName), but it doesn't have corresponding DNS host name.

Was it helpful?

Solution

The only reasonably check you can make is if IP is some sort of reserved IP. Otherwise there is not much you can do - even lack of "ping" (ICMP) responses and lack of responses on well-known ports (like HTTP - 80) means nothing.

Reserved as in:

  • 127.0.0.0/8 - loopback (may or may not be considered "valid host")
  • 224.0.0.0 - 239.255.255.255 - multicast (unlikely to be considered "valid host")
  • all zeros/all ones in subnet (i.e. 192.168.1.0 and 192.168.1.255 for 192.168.1.0/24 subnet) are all/broadcast - clearly not associated with particular how.

Check IP4 subnetting and linked RFCs for more info on special ranges/IPs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top