Validar una dirección IP

1963 vistas

Podemos hacerlo mediante expresiones regulares.

Usaremos el namespace System.Text.RegularExpressions.



csharp
  1. public bool CheckIpAddr(string ipAddress)
  2. {
  3.     string re = @"^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$";
  4.     return Regex.IsMatch(ipAddress, re);
  5. }



Y ahora una versión sin expresiones regulares.
Nos serviremos de la función Split de la clase String para parsear la cadena. Luego analizaremos las sub-cadenas.



csharp
  1. public bool CheckIpAddrNoRegex( string ipAddress )
  2. {
  3.     if ( ipAddress == null || ipAddress == "" )
  4.         return false;
  5.     string[] ipPartList = ipAddress.Split( '.' );
  6.     if ( ipPartList.Length != 4 )
  7.         return false;
  8.     try
  9.     {
  10.         byte ipPartNumber = Convert.ToByte( ipPartList[0] );
  11.         ipPartNumber = Convert.ToByte( ipPartList[1] );
  12.         ipPartNumber = Convert.ToByte( ipPartList[2] );
  13.         ipPartNumber = Convert.ToByte( ipPartList[3] );
  14.     }
  15.     catch ( Exception ) { return false; }
  16.     return true;
  17. }