Validar una dirección IP

2224 vistas


Podemos hacerlo mediante expresiones regulares.

Usaremos el namespace System.Text.RegularExpressions.



vbnet
  1. Public Function CheckIpAddr(ByVal ipAddress As String) As Boolean
  2.  
  3.     Dim re As String = "^(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.    
  6. End Function



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.



vbnet
  1. Public Function CheckIpAddrNoRegex(ByVal ipAddress As String) As Boolean
  2.  
  3.     Dim ipPartList As String()
  4.  
  5.     If ipAddress Is Nothing OrElse ipAddress = "" Then
  6.         Return False
  7.     End If
  8.  
  9.     ipPartList = ipAddress.Split("."c)
  10.     If Not (ipPartList.Length = 4) Then
  11.         Return False
  12.     End If
  13.  
  14.     Try
  15.         Dim ipPartNumber As Byte = Convert.ToByte(ipPartList(0))
  16.         ipPartNumber = Convert.ToByte(ipPartList(1))
  17.         ipPartNumber = Convert.ToByte(ipPartList(2))
  18.         ipPartNumber = Convert.ToByte(ipPartList(3))
  19.     Catch
  20.         Return False
  21.     End Try
  22.  
  23.     Return True
  24.  
  25. End Function