184k views
4 votes
Write a python program to read four numbers (representing the four octets of an IP) and print the next five IP addresses. Be sure to verify that the second, third and fourth numbers are between 0 and 255. The first one should be between 1 and 255.

User Haywood
by
6.0k points

1 Answer

4 votes

Answer:

first_octet = int(input("Enter the first octet: "))

second_octet = int(input("Enter the second octet: "))

third_octet = int(input("Enter the third octet: "))

forth_octet = int(input("Enter the forth octet: "))

octet_start = forth_octet + 1

octet_end = forth_octet + 6

if (1 <= first_octet <= 255) and (0 <= second_octet <= 255) and (0 <= third_octet <= 255) and (0 <= forth_octet <= 255):

for ip in range(octet_start, octet_end):

forth_octet = forth_octet + 1

if forth_octet > 255:

forth_octet = (forth_octet % 255) - 1

third_octet = third_octet + 1

if third_octet > 255:

third_octet = (third_octet % 255) - 1

second_octet = second_octet + 1

if second_octet > 255:

second_octet = (second_octet % 255) - 1

first_octet = first_octet + 1

if first_octet > 255:

print("No more available IP!")

break

print(str(first_octet) + "." + str(second_octet) + "." + str(third_octet) + "." + str(forth_octet))

else:

print("Invalid input!")

Step-by-step explanation:

- Ask the user for the octets

- Initialize the start and end points of the loop, since we will be printing next 5 IP range is set accordingly

- Check if the octets meet the restrictions

- Inside the loop, increase the forth octet by 1 on each iteration

- Check if octets reach the limit - 255, if they are greater than 255, calculate the mod and subtract 1. Then increase the previous octet by 1.

For example, if the input is: 1. 1. 20. 255, next ones will be:

1. 1. 21. 0

1. 1. 21. 1

1. 1. 21. 2

1. 1. 21. 3

1. 1. 21. 4

There is an exception for the first octet, if it reaches 255 and others also reach 255, this means there are no IP available.

- Print the result

User Abhineet
by
5.7k points