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?
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.
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.
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 ...
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With