Martin Buberl Martin Buberl - 1 month ago 12
C# Question

IP address validation

I'm refactoring my code and wanted to use the

method to validate if a string is a valid IPv4 address instead of using regular expressions:

public static bool IsIPv4(string value)
{
IPAddress address;

if (IPAddress.TryParse(value, out address))
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
return true;
}
}

return false;
}


My unit test is now failing because these input values return
true
and get parsed to the following
IPAddress
objects:

value = "0.0.0.0" -> address = {0.0.0.0}
value = "255.255.255" -> address = {255.255.0.255}
value = "65536" -> address = {0.1.0.0}


Does this make sense? I can see that
0.0.0.0
is technically a valid IPv4 address, even if it makes no sense for the user to enter that. What about the other two? Why are they converted in the way they are and should I treat them as valid even if it might not be transparent for the user, who maybe just forgot to enter the periods (
65536
instead of
6.5.5.36
).

Any help is most appreciated.

Answer

It looks like the docs for IPAddress.Parse rationalize this behavior by pointing out that entering fewer parts is convenient for entering class A and B addresses. If you want to force a four-part address, you might just want to check that there are three periods in the address before feeding it to IPAddress.TryParse, I guess.

Some code for your reference:

// verify that IP consists of 4 parts
if (value.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).Length == 4)
{
    IPAddress ipAddr;
    if (IPAddress.TryParse(value, out ipAddr))
    {
        // IP is valid
    }
    else
        // invalid IP
}
else
    // invalid IP
Comments