Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for IP addresses

Tags:

python

ip

ipv6

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

like image 700
Ivy Avatar asked Aug 06 '12 12:08

Ivy


2 Answers

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.

like image 141
Igor Chubin Avatar answered Sep 17 '22 19:09

Igor Chubin


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.

like image 30
John La Rooy Avatar answered Sep 19 '22 19:09

John La Rooy