ΩmegaMan
ΩmegaMan

Reputation: 31576

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?

Upvotes: 13

Views: 4369

Answers (3)

Leo
Leo

Reputation: 5122

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

Upvotes: 9

Nkosi
Nkosi

Reputation: 246998

You can take advantage of the System.Net.IPAddress.TryParse Method (String, IPAddress) and create an extension method to perform the desired functionality.

public static class IpAddressExtension {
    public static bool IsIPAddress(this string ipAddress) {
        System.Net.IPAddress address = null;
        return System.Net.IPAddress.TryParse(ipAddress, out address);
    }
}

This now allows the following

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

if (host.IsIPAddress()) {
    //...valid ip address
}

Upvotes: 7

Gururaj
Gururaj

Reputation: 539

One way you can do is use Dns.GetHostName() to get the HostName of the machine where this statement gets executed to compare against the value you've read from HOST header - something like this

var host = HttpContext.Current.Request.Headers["HOST"];
var machineHostName = Dns.GetHostName();

if(host.ToLower().Equals(machineHostName.ToLower()))
{
    // Perform your action here.
}

Upvotes: 0

Related Questions