I have a method to validate a parameter IP Address. Being new to development as a whole I would like to know if there is a better way of doing this.
/// <summary>
/// Check IP Address, will accept 0.0.0.0 as a valid IP
/// </summary>
/// <param name="strIP"></param>
/// <returns></returns>
public Boolean CheckIPValid(String strIP)
{
// Split string by ".", check that array length is 3
char chrFullStop = '.';
string[] arrOctets = strIP.Split(chrFullStop);
if (arrOctets.Length != 4)
{
return false;
}
// Check each substring checking that the int value is less than 255 and that is char[] length is !> 2
Int16 MAXVALUE = 255;
Int32 temp; // Parse returns Int32
foreach (String strOctet in arrOctets)
{
if (strOctet.Length > 3)
{
return false;
}
temp = int.Parse(strOctet);
if (temp > MAXVALUE)
{
return false;
}
}
return true;
}
Its simple (I could do it) but it seems to do the trick.
Surprised no one offered a Regex solution. All you need is to include System.Text.RegularExpressions. For readability both in actual code and for this example, I ALWAYS chunk my regex pattern into a string array and then join it.
try with this:
Why dont you use IPAddress.Parse or IPAddress.TryParse
If you want to just check if is valid do only:
bool isValid = IPAddress.TryParse(stringIP, out IPAddress _);
It will valid even if this is above 255 and if have dots, so no need to check it.
Without using IPAddress class and validating against byte, which is far better than the Int<256 approach.
The limitation with
IPAddress.TryParse
method is that it verifies if a string could be converted to IP address, thus if it is supplied with a string value like"5"
, it consider it as"0.0.0.5"
.Another approach to validate an IPv4 could be following :
It could be tested like:
The output will be:
You can also use
IPAddress.TryParse
but it has the limitations and could result in incorrect parsing.System.Net.IPAddress.TryParse Method
But this would work with normal string containing at least three dots. Something like:
With
IPAddress.TryParse
you can check for existence of three dots and then callTryParse
like: