views:

1957

answers:

2

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?

+17  A: 

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;
        }
    }
Erich Mirabal
Thanks! Not sure how I got this far without running across the System.Net.IPAddress class before.
Josh
No problem. The BCL is massive, as you know. I try to read through it every once in a while just to see what is out there.
Erich Mirabal
Same as what Josh has said. Excellent example. Thanks!
Matt Hanson
+4  A: 
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.

DrJokepu