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?
You can use this to try and parse it:
Then check
AddressFamily
whichEDIT: some sample code. change as desired:
You may use the IPAddress.GetAddressBytes().Length property
I guess should work
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.
You could check out System.Uri.CheckHostName( value ) that returns
Unknown
,Dns
,IPv4
,IPv6
.If
isValidIp
is true, you can checkipAddress.AddressFamily
to determine if it's IPv4 or IPv6. It'sAddressFamily.InterNetwork
for IPv4 andAddressFamily.InterNetworkV6
for IPv6.A combination of tests applied to a string or IPAddress, works for me..