2

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:"))
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ang peng hian
  • 33
  • 1
  • 7
  • Does this answer your question? [How to validate IP address in Python?](https://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python) – Georgy Jul 31 '20 at 13:51

5 Answers5

6

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • thank you for the answer, i managed to incorporate it into my code. unfortunately i do not understand the try: function yet. but i will learn about it – ang peng hian Jul 31 '20 at 13:26
  • 2
    @angpenghian `try..except` is how exceptions are handled in Python. If user enters invalid IP address, `ValueError` exception is thrown. More here for exemple: https://pythonbasics.org/try-except/ – Andrej Kesely Jul 31 '20 at 13:28
  • 1
    ahhh.. ok to understand u correctly so ipaddress.ip_address is the one which verify if the ip address is proper. and if it's proper the code will stop using the break but if return valueerror it will continue the code. thank you. learned something new. will understand the try function more – ang peng hian Jul 31 '20 at 13:42
  • hello, i would like some help i have changed your 'a' to 'wanip' but when i try to print(wanip) it says Name 'wanip' can be undefined is the a or wanip not a string or var? – ang peng hian Jul 31 '20 at 14:04
  • 1
    @angpenghian Probably you're editing your code through some IDE and it complains that `wanip` is undefined. Put `wanip = None` at the beginning, to remove the warning. – Andrej Kesely Jul 31 '20 at 15:59
  • yes i was using IDE, thank you i got it working – ang peng hian Aug 01 '20 at 03:21
3

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)
sortas
  • 1,527
  • 3
  • 20
  • 29
  • thank you, your answer seems the easiest but im not familiar with Regex when i tried i get "NameError: name 're' is not defined" i looked at the guide it did not state what re should be. – ang peng hian Jul 31 '20 at 13:31
  • 1
    Np, happens, I updated the answer :) `re` is the default library for Python, so you don't need to install anything else. – sortas Jul 31 '20 at 13:35
  • If there's any match - it's valid. If `None` - not valid. – sortas Jul 31 '20 at 13:37
  • thank you for the update. seems easier to understand now. just need to figure out how to add into my code. i understand it as it is. but my code requires to continue asking for next input instead of printing straight ;/ – ang peng hian Jul 31 '20 at 13:50
  • 1
    Updated it again a little bit :) If there's a bad IP, you need to stop processing and throw some error or smth, so the user could understand what's wrong. If IP is good - just continue asking below the code. – sortas Jul 31 '20 at 14:07
  • hello thank you for your update. i been playing around more on your code now and i understand it already. but i have a new issue. because Andrej Kesely codes allows me to loop back to the top if false im trying to do that with yours with no luck. i tired combing both yr code didnt work :( – ang peng hian Jul 31 '20 at 15:36
  • 1
    :) Updated once again. – sortas Jul 31 '20 at 15:45
  • OMG, i was so close to your answer.. i googled. mine didnt work because the loop always define back input to 0 but why isit yours u put ip=none? – ang peng hian Jul 31 '20 at 16:04
  • 1
    To initiate `ip` variable (to say Python we have it in "global" scope, and we're updating it and not creating it in the loop below). It's not required, just "better safe than sorry". – sortas Jul 31 '20 at 16:25
1

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
777moneymaker
  • 697
  • 4
  • 15
  • thank you for the answer yours seem similar to andrej's but i dont get the part. print(f'{ip} is correct. Version: IPv{ip.version}') as well as try. i am only at Boolean Expression True and False on udemy. just doing this as a small project for myself – ang peng hian Jul 31 '20 at 13:29
  • 1
    I recommend you reading this articles: https://www.python.org/dev/peps/pep-0498/ , https://docs.python.org/3/tutorial/errors.html – 777moneymaker Jul 31 '20 at 13:32
  • 1
    thank you will check the links u suggested. ah.. the f is the fstring. dam i need to practice more. it seems to be once of the basics – ang peng hian Jul 31 '20 at 13:46
1

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"
Addy
  • 417
  • 4
  • 13
  • thank you for the answer, i can see its similar to mateus as well. but i do not know how to include it in my code with user input – ang peng hian Jul 31 '20 at 13:36
1

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.

Mateus
  • 266
  • 1
  • 7
  • thank you for the answer, i can understand it as a stand alone. but i do not know how to add it into my code. :( – ang peng hian Jul 31 '20 at 13:34
  • What do you mean? You can copy that function into your code and whenever you have to check if an ip is valid, you can use `if isValid(theIpYouWantToVerify): doSomething`. – Mateus Jul 31 '20 at 13:58