Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python IP validation REGex validation for full and partial IPs

Im trying to validate the input to see if it a valid IP address(could be a partial one).

Acceptable input : 172, 172.112, 172.112.113, 172.112.113.114

Unacceptable input: 1724,172.11113 etc etc

Heres a function that I created to check it (however it validates unacceptable input like 1724 which I cant seem to fix..please help)

def ipcheck(ip):
    ippattern_str = '(([1-2]?[d]{1,2}.?){0,1}(.[1-2]?[d]{1,2}){0,1}(.[1-2]?[d]{1,2}.){0,1}(([1-2]?[d]{1,2}[DW]*)'
    ippattern = re.compile(ippattern_str)
    # ippattern is now used to call match, passing only the ip string
    global matchip
    matchip = ippattern.match(ip)
    return matchip


ip = sys.argv[1]
ipcheck(ip)

print matchip

I feel like maybe I need to use anchors properly? Ive tried everything to my best knowledge, any help would be appreciated.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Maybe you could avoid to use regex and let python socket.inet_aton do the job :

import socket

try:
    socket.inet_aton(addr)
    # correct IP
except socket.error:
    # bad IP

For inet_aton, a valid IP address is something of the form :

       a.b.c.d
       a.b.c
       a.b
       a

In all of the above forms, components of the dotted address can be specified in decimal, octal (with a leading 0), or hexadecimal, with a leading 0X). Addresses in any of these forms are collectively termed IPV4 numbers-and-dots notation. The form that uses exactly four decimal numbers is referred to as IPv4 dotted-decimal notation (or sometimes: IPv4 dotted-quad notation).

source


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...