Validating an IP String in C#


/ Published in: C#
Save to your folder(s)

Quick method to validate a string is a valid IP address.


Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// Check IP Address, will accept 0.0.0.0 as a valid IP
  3. /// </summary>
  4. /// <param name="strIP"></param>
  5. /// <returns></returns>
  6. public Boolean CheckIPValid(String strIP)
  7. {
  8. // Split string by ".", check that array length is 3
  9. char chrFullStop = '.';
  10. string[] arrOctets = strIP.Split(chrFullStop);
  11. if (arrOctets.Length != 4)
  12. {
  13. return false;
  14. }
  15. // Check each substring checking that the int value is less than 255 and that is char[] length is !> 2
  16. Int16 MAXVALUE = 255;
  17. Int32 temp; // Parse returns Int32
  18. foreach (String strOctet in arrOctets)
  19. {
  20. if (strOctet.Length > 3)
  21. {
  22. return false;
  23. }
  24.  
  25. temp = int.Parse(strOctet);
  26. if (temp > MAXVALUE)
  27. {
  28. return false;
  29. }
  30. }
  31. return true;
  32. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.