Checking for IP addresses

2019-01-26 10:03发布

Are there any existing libraries to parse a string as an ipv4 or ipv6 address, or at least identify whether a string is an IP address (of either sort)?

标签: python ip ipv6
8条回答
Root(大扎)
2楼-- · 2019-01-26 10:24

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.

查看更多
老娘就宠你
3楼-- · 2019-01-26 10:28

Try

apt-get install python-ipaddr

or get the source code from here

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-26 10:29

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.

查看更多
疯言疯语
5楼-- · 2019-01-26 10:29

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).

查看更多
虎瘦雄心在
6楼-- · 2019-01-26 10:32

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")
查看更多
做个烂人
7楼-- · 2019-01-26 10:35

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
查看更多
登录 后发表回答