Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

python - Checking for IP addresses

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...