C# helper function to validate whether or not the passed parameter string is a valid DNS name.
/// <summary>
/// Determines whether the DNS name is valid
/// </summary>
/// <remarks>
/// See RFC 2181, Section 11 https://tools.ietf.org/html/rfc2181
/// </remarks>
/// <param name="dnsName">The DNS name to validate.</param>
/// <returns>True if valid, false if not.</returns>
public static bool IsValidDnsName(string dnsName)
{
if (string.IsNullOrEmpty(dnsName))
{
return false;
}
int len = dnsName.Length;
if (len > 255)
{
return false;
}
int partLength = 0;
for (int i = 0; i < len; i++)
{
char c = dnsName[i];
if (c == '.')
{
if (i == 0 && len > 1)
{
return false; // Can't begin with a dot unless it's "."
}
if (i > 0 && partLength == 0)
{
return false; // No ".." allowed
}
partLength = 0;
continue;
}
partLength++;
if (partLength > 63)
{
return false;
}
}
return true;
}