Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if Host Is Resolved DNS Name Or IP

If one is extracting a HOST value from an HttpContext's HttpRequest's Headers collection, is there a way of determining if the value returned is a DNS resolved name or a direct IP address?

Example Usage

 string host = HttpContext.Current.Request.Headers["HOST"]; 

 if (host.IsIPAddress()) ... /// Something like this ?
     or
    (host.IsDNSResolved()) // Or this?

Summary

It is obvious that one could do a regex pattern test on the result to look for an IP pattern, but is there a property on HttpContext or more likely HttpRequest, or even an external static method off of a helper class which could do that determination instead?

like image 361
ΩmegaMan Avatar asked Oct 10 '15 13:10

ΩmegaMan


Video Answer


1 Answers

How about Uri.CheckHostName()?

This returns a System.UriHostNameType.

Example:

Uri.CheckHostName("127.0.0.1"); //=> IPv4
Uri.CheckHostName("www.google.com"); //=> Dns
Uri.CheckHostName("localhost"); //=> Dns
Uri.CheckHostName("2000:2000:2000:2000::"); //=> IPv6

Of course, to use the way you suggested, the easiest way is to create an extension, like so:

    public static class UriExtension {
        public static bool IsIPAddress(this string input) {
            var hostNameType = Uri.CheckHostName(input);

            return hostNameType == UriHostNameType.IPv4 || hostNameType == UriHostNameType.IPv6;
        }
    }

And this is the result:

"127.0.0.1".IsIPAddress(); //true
"2000:2000:2000:2000::".IsIPAddress(); //true
"www.google.com".IsIPAddress(); //false
like image 182
Leo Avatar answered Oct 20 '22 16:10

Leo