Martin Buberl Martin Buberl - 3 months ago 23
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
and get parsed to the following

value = "" -> address = {}
value = "255.255.255" -> address = {}
value = "65536" -> address = {}

Does this make sense? I can see that
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 (
instead of

Any help is most appreciated.


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
        // invalid IP
    // invalid IP