codekingpro/portable-devtools
114k
1""" Some helper functions for validation of ports and lists of ports. """2 3 4def check_port(port):5 """ Check if a port is valid. Return an error message indicating what is invalid if something isn't valid. """6 if isinstance(port, int):7 if port not in range(0, 65535):8 return 'Source port must in range from 0 to 65535'9 else:10 return 'Source port must be an integer'11 return None12 13 14def check_port_and_port_list(port, port_list):15 """ Take in a port and a port list and check that at most one is non-null. Additionally check that if either16 is non-null, it is valid.17 Return an error message indicating what is invalid if something isn't valid.18 """19 if port is not None and port_list is not None:20 return 'Cannot specify both a source port and a source port list'21 elif port is not None:22 if isinstance(port, int):23 if port not in range(0, 65535):24 return 'Source port must in range from 0 to 65535'25 else:26 return 'Source port must be an integer'27 elif port_list is not None:28 try:29 _ = iter(port_list)30 except TypeError:31 return 'Source port list must be an iterable {}'.format(port_list)32 33 for candidate_port in port_list:34 err = check_port(candidate_port)35 if err:36 return err37 return None38 