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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With