Getting IPv4 Range from user input

This program is trying to get the starting and ending IP from user input.

User Input Sample

Case 1. 10.244.1.0-100
Case 2. 10.244.1.0-11.245.0.1

For Case 1, the starting IP should be 10.244.1.0 while ending ip is 10.244.1.100
For Case 2, the starting IP should be 10.244.1.0 while ending ip is 11.245.0.1

Note that, form 1 can be 10.244.1.2-1 and form 2 can be 11.245.0.1-10.244.1.0

IPv4 Regex validate

1
2
3
4
5
6
7
def is_valid_ipv4(ip):
import re
pattern = "(?:(?: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])"
g = re.match(pattern, ip)
if g is not None:
return True
return False

Determine the starting and ending IP

1
2
3
4
5
6
7
8
9
def find_start_end_ip(first_ip, second_ip):
import re
pattern = "^(\d+)\.(\d+)\.(\d+)\.(\d+)$"
g1 = re.match(pattern, first_ip)
g2 = re.match(pattern, second_ip)
for i in range(1, 5):
if (g2.group(i) < g1.group(i)):
return second_ip, first_ip
return first_ip, second_ip

Main program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import re
count = 1
ip_range_pattern = 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]?))-((?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|(?:(?: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]?))$'

for input_case in test_case_list:
print("Input case {}".format(count))
count = count + 1
try:
result_groups = re.match(ip_range_pattern, input_case)
first_ip = result_groups.group(1) + result_groups.group(2)
if (is_valid_ipv4(result_groups.group(3))):
second_ip = result_groups.group(3)
else:
second_ip = result_groups.group(1) + result_groups.group(3)
start_ip, end_ip = find_start_end_ip(first_ip, second_ip)
print("Start IP: {}".format(start_ip))
print("End IP: {}".format(end_ip))
except Exception as e:
print("Invalid Input: {}".format(input_case))

Test Case Input:

1
2
3
4
5
6
7
test_case_list = ['10.244.1.0-256',
'10.244.2.0-10.244.2.222',
'10.244.3.0-10.244.4.33',
'10.244.5.0-10.255.3.1',
'10.211.3.0-13.23.5.2',
'10.211.3.0-9.1.1.255',
'10.211.4.5-10.211.4.3']

Test Case Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Input case 1
Invalid Input: 10.244.1.0-256
Input case 2
Start IP: 10.244.2.0
End IP: 10.244.2.222
Input case 3
Start IP: 10.244.3.0
End IP: 10.244.4.33
Input case 4
Start IP: 10.255.3.1
End IP: 10.244.5.0
Input case 5
Start IP: 10.211.3.0
End IP: 13.23.5.2
Input case 6
Start IP: 9.1.1.255
End IP: 10.211.3.0
Input case 7
Start IP: 10.211.4.3
End IP: 10.211.4.5

Tools / Acknowledgements

IP Address Regex: https://www.regular-expressions.info/ip.html
Regex Testing Online: https://regexr.com/