I am trying to determine whether a hard-coded string is a valid IPv4 or IPv6 address. I realized way too late that there's an IPAddress class, so I am trying to continue on with my unnecessarily difficult way. I have a findIPv4 method that works perfectly fine, but when I attempted to copy it and modify it slightly for the IPv6 method, it didn't work (because IPv6 uses hexadecimal and can have chars a-f). I think the problem lies in the !section.ToLowerInvariant().Contains('d') part of the if-statement, but I'm not sure.
public string findIPv6(string ipv6)
{
// This will split the user inputted string at every instance of a ':'
var bytes = ipv6.Split(':');
// If we do not have 8 bytes, it is not an IPv6 therefore return neither
if (bytes.Length != 8)
{
return "Neither";
}
// This will check if there is an integer between 1 and 50
int value;
if (Int32.TryParse(ipv6, out value) && (value <= 50 && value >= 1))
{
return "Neither";
}
foreach (var section in bytes)
{
// If the length of the parsed int is not equal to the length
// of the byte string or 0 > int < 9 or abcdef , return false
int s;
if (!Int32.TryParse(section, out s) || !s.ToString().Length.Equals(section.Length) || s < 0 || s > 9 || !section.ToLowerInvariant().Contains('a') || !section.ToLowerInvariant().Contains('b') || !section.ToLowerInvariant().Contains('c') || !section.ToLowerInvariant().Contains('d') || !section.ToLowerInvariant().Contains('e') || !section.ToLowerInvariant().Contains('f'))
{
return "Neither";
}
}
return "IPv6";
}