python判断子网掩码的合法性和子网掩码的网络号的合法性
#! /usr/bin/env python3
import sys
import os
import re
def check_network_address(address):
if not address:
return False
#re of ip
#pattern = "^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"
#re of ip/mask
pattern = "^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)(\/([0-9]$|[0-2][0-9]|3[0-2]))$"
if not re.match(pattern, address):
print("{0} error, ip address must like 192.168.1.110/24".format(address))
return False
else:
print("True")
return True
if __name__ == '__main__':
while True:
int_ip = input("input ip address like [192.168.1.110/24]:")
if not check_network_address(int_ip):
continue
else:
continue
执行结果
root@1:~/HCCB/nlp/tools# ./check_address_mask.py
input ip address like [192.168.1.110/24]:11.11.11.11/16
True
input ip address like [192.168.1.110/24]:11.11.11.11/33
11.11.11.11/33 error, ip address must like 192.168.1.110/24
input ip address like [192.168.1.110/24]:11.11.11.11
11.11.11.11 error, ip address must like 192.168.1.110/24
input ip address like [192.168.1.110/24]:11.11.11.11/1
True
input ip address like [192.168.1.110/24]:11.11.11/24
11.11.11/24 error, ip address must like 192.168.1.110/24