Checking for IP addresses

末鹿安然 提交于 2019-11-29 10:06:56

Yes, there is ipaddr module, that can you help to check if a string is a IPv4/IPv6 address, and to detect its version.

import ipaddr
import sys

try:
   ip = ipaddr.IPAddress(sys.argv[1])
   print '%s is a correct IP%s address.' % (ip, ip.version)
except ValueError:
   print 'address/netmask is invalid: %s' % sys.argv[1]
except:
   print 'Usage : %s  ip' % sys.argv[0]

But this is not a standard module, so it is not always possible to use it. You also try using the standard socket module:

import socket

try:
    socket.inet_aton(addr)
    print "ipv4 address"
except socket.error:
    print "not ipv4 address"

For IPv6 addresses you must use socket.inet_pton(socket.AF_INET6, address).

I also want to note, that inet_aton will try to convert (and really convert it) addresses like 10, 127 and so on, which do not look like IP addresses.

John La Rooy

For IPv4, you can use

socket.inet_aton(some_string)

If it throws an exception, some_string is not a valid ip address

For IPv6, you can use:

socket.inet_pton(socket.AF_INET6, some_string)

Again, it throws an exception, if some_string is not a valid address.

IPv4 + IPv6 solution relying only on standard library. Returns 4 or 6 or raises ValueError.

try:
    # Python 3.3+
    import ipaddress

    def ip_kind(addr):
        return ipaddress.ip_address(addr).version

except ImportError:
    # Fallback
    import socket

    def ip_kind(addr):
        try:
            socket.inet_aton(addr)
            return 4
        except socket.error: pass
        try:
            socket.inet_pton(socket.AF_INET6, addr)
            return 6
        except socket.error: pass
        raise ValueError(addr)

You can use the netaddr library. It has valid_ipv4/valid_ipv6 methods:

import netaddr
if netaddr.valid_ipv4(str_ip) is True:
    print("IP is IPv4")
else:
    if netaddr.valid_ipv6(str_ip) is True:
        print("IP is IPv6")

ipaddr -- Google's IP address manipulation package.

Note that a proposal to include a revised version of the package in the Python standard library has recently been accepted (see PEP 3144).

Try

apt-get install python-ipaddr

or get the source code from here

If you know for sure that the address is valid and only trying to decide whether it is ipv4 or ipv6, wouldn't it be sufficient to do just:

if ":" in address:
    print("Ipv6")
else:
    print("Ipv4")

I prefer ip_interface because it handles situations both with and without prefix mask, for example, both "10.1.1.1/24" as well as simply "10.1.1.1". Needless to say, works for both v4 as well as v6

from ipaddress import ip_interface
ip_interface("10.1.1.1/24").ip
ip_interface("10.1.1.1/24").ip.version
ip_interface("10.1.1.1").ip
ip_interface("10.1.1.1").ip.version
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!