Params: Add parameter types for IP addresses in various forms.
New parameter forms are: IP address in the format "a.b.c.d" where a-d are from decimal 0 to 255. IP address with netmask which is an IP followed by "/n" where n is a netmask length in bits from decimal 0 to 32 or by "/e.f.g.h" where e-h are from decimal 0 to 255 and which is all 1 bits followed by all 0 bits when represented in binary. These can also be specified as an integral IP and netmask passed in separately. IP address with port which is an IP followed by ":p" where p is a port index from decimal 0 to 65535. These can also be specified as an integral IP and port value passed in separately.
This commit is contained in:
@@ -248,3 +248,52 @@ def toMemorySize(value):
|
||||
return long(value[:-1])
|
||||
|
||||
raise ValueError, "cannot convert '%s' to memory size" % value
|
||||
|
||||
def toIpAddress(value):
|
||||
if not isinstance(value, str):
|
||||
raise TypeError, "wrong type '%s' should be str" % type(value)
|
||||
|
||||
bytes = value.split('.')
|
||||
if len(bytes) != 4:
|
||||
raise ValueError, 'invalid ip address %s' % value
|
||||
|
||||
for byte in bytes:
|
||||
if not 0 <= int(byte) <= 0xff:
|
||||
raise ValueError, 'invalid ip address %s' % value
|
||||
|
||||
return (int(bytes[0]) << 24) | (int(bytes[1]) << 16) | \
|
||||
(int(bytes[2]) << 8) | (int(bytes[3]) << 0)
|
||||
|
||||
def toIpNetmask(value):
|
||||
if not isinstance(value, str):
|
||||
raise TypeError, "wrong type '%s' should be str" % type(value)
|
||||
|
||||
(ip, netmask) = value.split('/')
|
||||
ip = toIpAddress(ip)
|
||||
netmaskParts = netmask.split('.')
|
||||
if len(netmaskParts) == 1:
|
||||
if not 0 <= int(netmask) <= 32:
|
||||
raise ValueError, 'invalid netmask %s' % netmask
|
||||
return (ip, int(netmask))
|
||||
elif len(netmaskParts) == 4:
|
||||
netmaskNum = toIpAddress(netmask)
|
||||
if netmaskNum == 0:
|
||||
return (ip, 0)
|
||||
testVal = 0
|
||||
for i in range(32):
|
||||
testVal |= (1 << (31 - i))
|
||||
if testVal == netmaskNum:
|
||||
return (ip, i + 1)
|
||||
raise ValueError, 'invalid netmask %s' % netmask
|
||||
else:
|
||||
raise ValueError, 'invalid netmask %s' % netmask
|
||||
|
||||
def toIpWithPort(value):
|
||||
if not isinstance(value, str):
|
||||
raise TypeError, "wrong type '%s' should be str" % type(value)
|
||||
|
||||
(ip, port) = value.split(':')
|
||||
ip = toIpAddress(ip)
|
||||
if not 0 <= int(port) <= 0xffff:
|
||||
raise ValueError, 'invalid port %s' % port
|
||||
return (ip, int(port))
|
||||
|
||||
Reference in New Issue
Block a user