How to determine if a string is a valid IPv4 or IPv6 address in C#?

Josh picture Josh · Apr 28, 2009 · Viewed 91.1k times · Source

I know regex is dangerous for validating IP addresses because of the different forms an IP address can take.

I've seen similar questions for C and C++, and those were resolved with a function that doesn't exist in C# inet_ntop()

The .NET solutions I've found only handle the standard "ddd.ddd.ddd.ddd" form. Any suggestions?

Answer

Erich Mirabal picture Erich Mirabal · Apr 28, 2009

You can use this to try and parse it:

 IPAddress.TryParse

Then check AddressFamily which

Returns System.Net.Sockets.AddressFamily.InterNetwork for IPv4 or System.Net.Sockets.AddressFamily.InterNetworkV6 for IPv6.

EDIT: some sample code. change as desired:

    string input = "your IP address goes here";

    IPAddress address;
    if (IPAddress.TryParse(input, out address))
    {
        switch (address.AddressFamily)
        {
            case System.Net.Sockets.AddressFamily.InterNetwork:
                // we have IPv4
                break;
            case System.Net.Sockets.AddressFamily.InterNetworkV6:
                // we have IPv6
                break;
            default:
                // umm... yeah... I'm going to need to take your red packet and...
                break;
        }
    }