How do you determine if an IP address is private, in Python?

前端 未结 7 1207
Happy的楠姐
Happy的楠姐 2020-12-02 18:48

In Python, what is the best way to determine if an IP address (e.g., \'127.0.0.1\' or \'10.98.76.6\') is on a private network? The code does not s

相关标签:
7条回答
  • This is the fixed version of the regex approach suggested by @Kurt including the fix recommended by @RobEvans

    • ^127.\d{1,3}.\d{1,3}.\d{1,3}$
    • ^10.\d{1,3}.\d{1,3}.\d{1,3}$
    • ^192.168.\d{1,3}.\d{1,3}$
    • ^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}$

      def is_ip_private(ip):
      
          # https://en.wikipedia.org/wiki/Private_network
      
          priv_lo = re.compile("^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
          priv_24 = re.compile("^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
          priv_20 = re.compile("^192\.168\.\d{1,3}.\d{1,3}$")
          priv_16 = re.compile("^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}$")
      
          res = priv_lo.match(ip) or priv_24.match(ip) or priv_20.match(ip) or priv_16.match(ip)
          return res is not None
      
    0 讨论(0)
提交回复
热议问题