w3resource

Python: Valid an IP address

Python Basic: Exercise-139 with Solution

Write a Python program to valid an IP address.

From Wikipedia,
An Internet Protocol address (IP address) is a numerical label assigned to each device connected to a computer network that uses the Internet Protocol for communication. An IP address serves two main functions: host or network interface identification and location addressing.
Internet Protocol version 4 (IPv4) defines an IP address as a 32-bit number. However, because of the growth of the Internet and the depletion of available IPv4 addresses, a new version of IP (IPv6), using 128 bits for the IP address, was standardized in 1998. IPv6 deployment has been ongoing since the mid-2000s.
IP addresses are written and displayed in human-readable notations, such as 172.16.254.1 in IPv4, and 2001:db8:0:1234:0:567:8:1 in IPv6. The size of the routing prefix of the address is designated in CIDR notation by suffixing the address with the number of significant bits, e.g., 192.168.1.15/24, which is equivalent to the historically used subnet mask 255.255.255.0.

Sample Solution-1:

Python Code:

import socket
addr = '127.0.0.2561'
try:
    socket.inet_aton(addr)
    print("Valid IP")
except socket.error:
    print("Invalid IP")

Sample Output:

Invalid IP  

Flowchart:

Flowchart: Valid an IP address.

Sample Solution-2:

Python Code:

import re
ip_regex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"
def check_ip_address(user_ip):
   if(re.search(ip_regex, user_ip)):
       return "Valid Ip address"        
   else:
       return "Invalid Ip address"
user_ip = "10.0.0.0"
print("\n",user_ip,"->",check_ip_address(user_ip))
user_ip = "10.255.255.255"
print("\n",user_ip,"->",check_ip_address(user_ip))
user_ip = "192.168.255.0"
print("\n",user_ip,"->",check_ip_address(user_ip))
user_ip = "266.1.0.2"
print("\n",user_ip,"->",check_ip_address(user_ip))
user_ip = "01.102.103.104"
print("\n",user_ip,"->",check_ip_address(user_ip))

Sample Output:

 10.0.0.0 -> Valid Ip address

 10.255.255.255 -> Valid Ip address

 192.168.255.0 -> Valid Ip address

 266.1.0.2 -> Invalid Ip address

 01.102.103.104 -> Invalid Ip address  

Flowchart:

Flowchart: Valid an IP address.

Python Code Editor:

 

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to convert true to 1 and false to 0.
Next: Write a Python program to convert an integer to binary keep leading zeros.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Try-catch-else construct:

try:
  foo() 
except Exception: 
  print("Exception occured")
else:
  print("Exception didnt occur")
finally:
  print("Always gets here")