-1

I have the following code:

while True:
            try:
                HOST = input(float(('Enter host IP'))
            except ValueError:
                print('Error. That is not a valid IP address.')
                continue

I require the user to input an IP address. I wanted to set an error so that if he uses a letter he gets an error. How can I do that and why isn't my code working?

jamjam46
  • 75
  • 9
  • You can't convert a string to a float so this code isn't checking anything as the code will always throw an error – Larsluph Jan 05 '21 at 13:42
  • I'd probably use regex validation for an IP adress in the if statement. – Leemosh Jan 05 '21 at 13:44
  • How can I fix this? I'm new to python – jamjam46 Jan 05 '21 at 13:44
  • It's a bit unclear exactly what you want to achieve, but it sounds like you want to `raise ValueError` if the input does not match an IP address. Use `re` to check the input, and if it doesn't match `raise` a `ValueError`. – bicarlsen Jan 05 '21 at 13:45
  • Can you please put that in code? I'm kinda new to python – jamjam46 Jan 05 '21 at 13:48

3 Answers3

0

Try something like this

while True:
    try:
        HOST = input('Enter host IP: ')
        if len(HOST.split(".")) != 4:
            raise ValueError
        for char in HOST:
            if char not in "0123456789.":
                raise ValueError
    except ValueError:
        print('Error. That is not a valid IP address.')
        continue
    else:
        break
Larsluph
  • 162
  • 2
  • 11
0

There is no need for the try/except. You just need an IP validation. This code should be working.

import re

while True:
    HOST = input("Enter IP adress: ")
    if re.match(
        r"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$",
        HOST,
    ):
        print(f"{inp} is valid IP adress")
        break
    else:
        print("Enter valid IP adress")
Leemosh
  • 883
  • 6
  • 19
0

I will begin by pointing out a few problems with your submitted code. First of all, your code will never exit the while loop, since you have provided no break out. Secondly, a valid IP address takes the form of something along the lines of 192.168.2.10 for IPV4 or "2001:0db8:0a0b:12f0:0000:0000:0000:0001" for IPV6, and which can never be interpreted as a float, so you will always generate a value error response. In order to validate an IP addfress correctly checkout the following check if a string matches an IP address pattern in python?.

import ipaddress
Host = None
while True:
    try:
        Host = ipaddress.ip_address(input('Enter host IP'))
        break
    except:
        print('Error. That is not a valid IP address.')
        continue
itprorh66
  • 3,110
  • 4
  • 9
  • 21