Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 613
Josh Avatar asked Apr 28 '09 17:04

Josh


People also ask

How do I know if a string is IPv4 or IPv6?

Given a string S consisting of N characters, the task is to check if the given string S is IPv4 or IPv6 or Invalid. If the given string S is a valid IPv4, then print “IPv4”, if the string S is a valid IPv6, then print “IPv4”. Otherwise, print “-1”. A valid IPv4 address is an IP in the form “x1.

How do you check IP address is IPv4 or IPv6 in C?

You could use inet_pton() to try parsing the string first as an IPv4 ( AF_INET ) then IPv6 ( AF_INET6 ). The return code will let you know if the function succeeded, and the string thus contains an address of the attempted type.

How do I know if a IPv6 address is valid?

Typically strings, that do *not* trepresent a valid IPv6 address have characters other than the hex-digits in it, or they consists of less than 8 blocks of hexdigits, or they have at least one block of hexdigits in it with more than 4 hex-digits, or they have more than one position in it, where 2 colons directly follow ...


1 Answers

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;         }     } 
like image 87
Erich Mirabal Avatar answered Sep 28 '22 08:09

Erich Mirabal