| 1 |
import re |
| 2 |
|
| 3 |
|
| 4 |
_hostname_re = re.compile('(?!-)[A-Z\d-]{1,63}(?<!-)$', re.IGNORECASE) |
| 5 |
|
| 6 |
|
| 7 |
def valid_address(address): |
| 8 |
""" |
| 9 |
Determines whether the specified address string is valid. |
| 10 |
""" |
| 11 |
if not address: |
| 12 |
return False |
| 13 |
|
| 14 |
components = str(address).split(':') |
| 15 |
if len(components) > 2 or not valid_hostname(components[0]): |
| 16 |
return False |
| 17 |
|
| 18 |
if len(components) == 2 and not valid_port(components[1]): |
| 19 |
return False |
| 20 |
|
| 21 |
return True |
| 22 |
|
| 23 |
|
| 24 |
def valid_hostname(host): |
| 25 |
""" |
| 26 |
Returns whether the specified string is a valid hostname. |
| 27 |
""" |
| 28 |
if len(host) > 255: |
| 29 |
return False |
| 30 |
|
| 31 |
if host[-1:] == '.': |
| 32 |
host = host[:-1] |
| 33 |
|
| 34 |
return all(_hostname_re.match(c) for c in host.split('.')) |
| 35 |
|
| 36 |
|
| 37 |
def valid_port(port): |
| 38 |
""" |
| 39 |
Returns whether the specified string is a valid port, |
| 40 |
including port 0 (random port). |
| 41 |
""" |
| 42 |
try: |
| 43 |
return 0 <= int(port) <= 65535 |
| 44 |
except: |
| 45 |
return False |