insta answer was closer before he added the wrong regular expression.
public static bool IsValidIP(string ipAddress) { IPAddress unused; return IPAddress.TryParse(ipAddress, out unused); }
Or, since the OP does not want to include integer IPv4 addresses that are not full dotted squares:
public static bool IsValidIP(string ipAddress) { IPAddress unused; return IPAddress.TryParse(ipAddress, out unused) && ( unused.AddressFamily != AddressFamily.InterNetwork || ipAddress.Count(c => c == '.') == 3 ); }
Testing:
IsValidIP("fe80::202:b3ff:fe1e:8329")
returns true
(correct).
IsValidIP("127.0.0.1")
returns true
(correct).
IsValidIP("What an IP address?")
Returns false
(correct).
IsValidIP("127")
returns true
with the first version false
with the second (correct).
IsValidIP("127.0")
returns true
with the first version false
with the second (correct).
source share