Validate IP Address in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string; we have to check whether the given input is a valid IPv4 address or IPv6 address or neither.

The IPv4 addresses are canonically represented in dotted-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), For example,; Besides, leading zeros in the IPv4 address is invalid. For example, the address is invalid.

The IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, suppose the address is 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid address. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 this address is also a valid

However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. So for example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. Besides, extra leading zeros in the IPv6 is also invalid. The address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid.

To solve this, we will follow these steps −

  • Define a method checkv4(x), this will check whether x is in range 0 to 255, then true, otherwise false

  • Define a method checkv6(x), this will work as follows −

    • if size of x > 4, then return false

    • if decimal equivalent of x >= 0 and x[0] is not ‘-’, then return true, otherwise false

  • From the main method

  • If the input has three dots, and for each part I checkv4(i) is true, then return “IPv4”

  • If the input has seven colons, and for each part I checkv6(i) is true, then return “IPv6”

Example (Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def validIPAddress(self, IP):
      :type IP: str
      :rtype: str
      def isIPv4(s):
         try: return str(int(s)) == s and 0 <= int(s) <= 255
         except: return False
      def isIPv6(s):
         if len(s) > 4:
            return False
         try : return int(s, 16) >= 0 and s[0] != '-'
            return False
      if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")):
         return "IPv4"
      if IP.count(":") == 7 and all(isIPv6(i) for i in IP.split(":")):
         return "IPv6"
      return "Neither"
ob = Solution()




Published on 31-Mar-2020 12:28:21