Ticket #2461: iputils.py

File iputils.py, 2.5 KB (added by jvargas -a-t- acm -*- org, 18 years ago)

django/utils/iputils.py module

Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3"""Miscellaneous IPv4 Utilities"""
4
5## ip utils
6
7def is_valid_ipv4_addr(address):
8 """is_valid_ipv4_addr(ip_addr) -> bool
9
10 returns True if address is a valid IPv4 address
11
12 Examples:
13
14 >>> is_valid_ipv4_addr('asdf')
15 False
16 >>> is_valid_ipv4_addr('a.b.c.d')
17 False
18 >>> is_valid_ipv4_addr('2.3.4.5')
19 True
20 >>> is_valid_ipv4_addr('127.0.0.1')
21 True
22 >>> is_valid_ipv4_addr('django.py')
23 False
24 >>> is_valid_ipv4_addr('256.23.2.2')
25 False
26 >>> is_valid_ipv4_addr('0.0.0.0')
27 True
28 >>> is_valid_ipv4_addr('25.25.25.25')
29 True
30 """
31 return 4 == (1 + address.count(".")) == \
32 len([n for n in address.split(".")
33 if (n.isdigit() and -1 < int(n) < 256)])
34
35def is_valid_ipv4_port(port):
36 """is_valid_ipv4_port(port) -> bool
37
38 returns True if 'port' is a valid IPv4 port
39
40 Examples:
41
42 Known good ports
43
44 >>> is_valid_ipv4_port(80)
45 True
46
47 Minimum good port
48
49 >>> is_valid_ipv4_port(0)
50 True
51
52 Maximum good port
53
54 >>> is_valid_ipv4_port(65535)
55 True
56
57 A string
58
59 >>> is_valid_ipv4_port('25')
60 True
61
62 Known bad ports
63
64 >>> is_valid_ipv4_port(65536)
65 False
66
67 >>> is_valid_ipv4_port(-1)
68 False
69 """
70 return str(port).isdigit() and -1 < int(port) < 65536
71
72def make_ipv4_host_port(host_port=None, default_host="127.0.0.1", default_port=8000):
73 """make_ipv4_host_port([host_port, default_host, default_port]) -> tuple
74
75 returns a valid host/port tuple from string 'host_port'
76
77 Examples:
78
79 >>> make_ipv4_host_port()
80 ('127.0.0.1', 8000)
81
82 >>> make_ipv4_host_port('168.223.2.25')
83 ('168.223.2.25', 8000)
84
85 >>> make_ipv4_host_port('bad bad')
86 ('127.0.0.1', 8000)
87
88 >>> make_ipv4_host_port('bad too', default_host='127.0.0.1')
89 ('127.0.0.1', 8000)
90
91 >>> make_ipv4_host_port('666.77.23.32:1')
92 ('127.0.0.1', 1)
93
94 >>> make_ipv4_host_port('25.32.15.15:81')
95 ('25.32.15.15', 81)
96 """
97 if not host_port:
98 return (default_host, default_port)
99 address = host_port.split(":", 1)
100 (addr_index, port_index) = (len(address) == 2) and (0, 1) or (0, 0)
101 ip_addr = is_valid_ipv4_addr(address[addr_index]) and \
102 (address[addr_index]) or \
103 default_host
104 ip_port = is_valid_ipv4_port(address[port_index]) and \
105 (int(address[port_index])) or \
106 default_port
107 return (ip_addr, ip_port)
108
109#### doctests
110##if __name__ == '__main__':
111## import doctest
112## doctest.testmod()
113##
Back to Top