Check if valid ip address from user input

Viewed 3264

I'm new to Python, and would like help for my code below. I like to be able to verify if the end user has key in a valid IP address. I searched online, and all the examples are too complex to understand hence I'm asking.

If possible would like the code to also loop back if the person input a invalid value.

input = 61.1.1.1

wanip = str(input("please key in WAN IP address:"))
5 Answers

You can use ipaddress module.

For example:

import ipaddress

while True:
    try:
        a = ipaddress.ip_address(input('Enter IP address: '))
        break
    except ValueError:
        continue

print(a)

Prints (for example):

Enter IP address: s
Enter IP address: a
Enter IP address: 1.1.1.1
1.1.1.1

There're multiple ways of doing it, if you want the simple one, based on this guide, you can use RegExp like this:

import re
check = re.match(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', YOUR_STRING)
if check:
    print('IP valid')
else:
    print('IP not valid')

In your situation it must look like:

wanip = str(input("please key in WAN IP address:"))
if not re.match(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', wanip):
    # Throw error here
# Continue with your code

If in loop:

import re

ip = None
while True:
    ip = str(input("please key in WAN IP address:"))
    if re.match(r'^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', ip):
        # Say something to user
        break
    else:
        # Say something to user
        continue
print(ip)

Code:

import ipaddress

try:
    user_ip = input("Enter adress: ")
    ip = ipaddress.ip_address(user_ip)
    print(f'{ip} is correct. Version: IPv{ip.version}')
except ValueError:
    print('Adress is invalid')

Example of usage:

Enter adress: 23
Adress is invalid

Enter adress: 154.123.1.34
154.123.1.34 is correct. Version: IPv4

Check this out

def validIPAddress(self, IP):
        
        def isIPv4(s):
            try: return str(int(s)) == s and 0 <= int(s) <= 255
            except: return False
            
        def isIPv6(s):
            if len(s) > 4: return False
            try: return int(s, 16) >= 0 and s[0] != '-'
            except: return False

        if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")): 
            return "IPv4"
        if IP.count(":") == 7 and all(isIPv6(i) for i in IP.split(":")): 
            return "IPv6"
        return "Neither"

I think an even simpler solution would be to do this:

def isValid(ip):
    ip = ip.split(".")

    for number in ip:
        if not number.isnumeric() or int(number) > 255:
            return False
    
    return True

Even though using regex would probably be a better solution, I am not sure if you are already familiar with it.

Related