How to validate IP address in Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bkunjitam
    New Member
    • Nov 2006
    • 17

    How to validate IP address in Python

    Hi,

    My programme has a text box where in user enters the ip address. I need to validate the IP (like no space allowed in the entry, the numerals should not exceed 255, not more than 3 dots allowed overall, no consecutive dots allowed etc.,.). How do i go about the same? Is there any built in function for the same?

    thanks,
    Badri
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by bkunjitam
    Hi,

    My programme has a text box where in user enters the ip address. I need to validate the IP (like no space allowed in the entry, the numerals should not exceed 255, not more than 3 dots allowed overall, no consecutive dots allowed etc.,.). How do i go about the same? Is there any built in function for the same?

    thanks,
    Badri
    Badri,

    This may cover most of of your requirements:
    Code:
    ip_str = "23.34.45.45"
    
    def ipFormatChk(ip_str):
        if len(ip_str.split()) == 1:
            ipList = ip_str.split('.')
            if len(ipList) == 4:
                for i, item in enumerate(ipList):
                    try:
                        ipList[i] = int(item)
                    except:
                        return False
                    if not isinstance(ipList[i], int):
                        return False
                if max(ipList) < 256:
                    return True
                else:
                    return False
            else:
                return False
        else:
            return False
        
    print ipFormatChk(ip_str)
    True

    Comment

    • bartonc
      Recognized Expert Expert
      • Sep 2006
      • 6478

      #3
      Nice coding, BV!

      Originally posted by bvdet
      Badri,

      This may cover most of of your requirements:
      Code:
      ip_str = "23.34.45.45"
      
      def ipFormatChk(ip_str):
          if len(ip_str.split()) == 1:
              ipList = ip_str.split('.')
              if len(ipList) == 4:
                  for i, item in enumerate(ipList):
                      try:
                          ipList[i] = int(item)
                      except:
                          return False
                      if not isinstance(ipList[i], int):
                          return False
                  if max(ipList) < 256:
                      return True
                  else:
                      return False
              else:
                  return False
          else:
              return False
          
      print ipFormatChk(ip_str)
      True

      Comment

      • MDunderdale
        New Member
        • Nov 2006
        • 1

        #4
        You can also use regular expressions like this
        Code:
        import re
        ip_str = "23.34.45.45"
        
        def ipFormatChk(ip_str):
           pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
           if re.match(pattern, ip_str):
              return True
           else:
              return False
        print ipFormatChk(ip_str)

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          Originally posted by MDunderdale
          You can also use regular expressions like this
          Code:
          import re
          ip_str = "23.34.45.45"
          
          def ipFormatChk(ip_str):
             pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
             if re.match(pattern, ip_str):
                return True
             else:
                return False
          print ipFormatChk(ip_str)
          Regular expressions are ideal for this application. This code executes much faster than the other. The drawback is readability. An alternative is to set the VERBOSE flag and add comments:
          Code:
          pattern = re.compile(r"""
             \b                                           # matches the beginning of the string
             (25[0-5]|                                    # matches the integer range 250-255 OR
             2[0-4][0-9]|                                 # matches the integer range 200-249 OR
             [01]?[0-9][0-9]?)                            # matches any other combination of 1-3 digits below 200
             \.                                           # matches '.'
             (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
             \.                                           # matches '.'
             (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
             \.                                           # matches '.'
             (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
             \b                                           # matches the end of the string
             """, re.VERBOSE)
          It executes slower, but I guess you can't have everything! Thanks for posting Mike.

          Comment

          • bartonc
            Recognized Expert Expert
            • Sep 2006
            • 6478

            #6
            Originally posted by bvdet
            Regular expressions are ideal for this application. This code executes much faster than the other. The drawback is readability. An alternative is to set the VERBOSE flag and add comments:
            Code:
            pattern = re.compile(r"""
               \b                                           # matches the beginning of the string
               (25[0-5]|                                    # matches the integer range 250-255 OR
               2[0-4][0-9]|                                 # matches the integer range 200-249 OR
               [01]?[0-9][0-9]?)                            # matches any other combination of 1-3 digits below 200
               \.                                           # matches '.'
               (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
               \.                                           # matches '.'
               (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
               \.                                           # matches '.'
               (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)       # repeat
               \b                                           # matches the end of the string
               """, re.VERBOSE)
            It executes slower, but I guess you can't have everything! Thanks for posting Mike.
            I like you style, BV.

            Comment

            Working...