0

I am writing a simple client and server and want to introduce some simple bounds checking to insure the IP address entered by a user is in the correct format i.e.(int.int.int.int), does anybody have any suggestions as to hwo this can be done at the moment my code just accepts the value and will throw an OS error if its invalid. But I want to stop a user being able to enter anything in here.

 def ipEntered():
          global ipEntered
          ipEntered = input("Please enter the ip address of the server you wish to connect with:")

Thanks

1
  • Don't forget to allow hex:hex:hex... etc. as well - IOW: to support IPv6. We have 2013 meanwhile! Commented Mar 20, 2013 at 15:57

1 Answer 1

3

Use the ipaddress module (introduced in Python 3.3):

import ipaddress

def ipEntered():
    while True:
        try:
            val = input("Please enter the ip address of the server you wish to connect with:")
            return ipaddress.ip_address(val)
        except ValueError:
            print("Not a valid IP address")

which will accept IPv4 addresses of the form "100.200.30.40", e.g. a dotted quad, and IPv6 addresses in both longhand form (8 groups of 4 hexadecimal characters separated by :) and shorthand forms.

If you only want to accept IPv4 addresses, use return ipaddress.IPv4Address(val) instead.

Sign up to request clarification or add additional context in comments.

5 Comments

Will this work if the user enters an ip address format already, lets say the user enters 172.0.0.1 or does it create an ip address using an int like 172001?
I think it's worth noting that this module will accept all of the different ways that an IP address can be expessed, not just the four-numbers-separated-by-periods form; in the code as you wrote it it will also accept IPv6 addresses. The former is probably a good idea (users may have a good reason to express an IP address in one of the other forms) but whether the latter is acceptable will depend on what the application is going to do with this IP address later.
@MartinAtkins: Indeed; it is to be hoped that anyone wanting to use a recommended module reads the documentation though. :-)
@MartinAtkins: But note that because input() is used, only strings are going to be passed in and in that case the module only accepts IPv4 addresses in the 4-octed dotted form, and IPv6 addresses in full form or shorthand notation.
Thanks for the advice, this application is only being used to demonstrate a prototype device so IPv4 is sufficent at this present time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.