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

Solution 1:

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;
        }
    }

Solution 2:

Just a warning about using System.Net.IpAddress.TryParse():

If you pass it an string containing an integer (e.g. "3") the TryParse function will convert it to "0.0.0.3" and, therefore, a valid InterNetworkV4 address. So, at the very least, the reformatted "0.0.0.3" should be returned to the user application so the user knows how their input was interpreted.

Solution 3:

string myIpString = "192.168.2.1";
System.Net.IPAddress ipAddress = null;

bool isValidIp = System.Net.IPAddress.TryParse(myIpString, out ipAddress);

If isValidIp is true, you can check ipAddress.AddressFamily to determine if it's IPv4 or IPv6. It's AddressFamily.InterNetwork for IPv4 and AddressFamily.InterNetworkV6 for IPv6.

Solution 4:

You could check out System.Uri.CheckHostName( value ) that returns Unknown , Dns, IPv4, IPv6.

if( Uri.CheckHostName( value ) != UriHostNameType.Unknown)
    //then 'value' is a valid IP address or hostname