1# Copyright (c) 2005 The Regents of The University of Michigan 2# All rights reserved. 3# 4# Redistribution and use in source and binary forms, with or without 5# modification, are permitted provided that the following conditions are 6# met: redistributions of source code must retain the above copyright 7# notice, this list of conditions and the following disclaimer; 8# redistributions in binary form must reproduce the above copyright --- 234 unchanged lines hidden (view full) --- 243 elif value.endswith('MB'): 244 return long(value[:-2]) * mebi 245 elif value.endswith('kB'): 246 return long(value[:-2]) * kibi 247 elif value.endswith('B'): 248 return long(value[:-1]) 249 250 raise ValueError, "cannot convert '%s' to memory size" % value |
251 252def toIpAddress(value): 253 if not isinstance(value, str): 254 raise TypeError, "wrong type '%s' should be str" % type(value) 255 256 bytes = value.split('.') 257 if len(bytes) != 4: 258 raise ValueError, 'invalid ip address %s' % value 259 260 for byte in bytes: 261 if not 0 <= int(byte) <= 0xff: 262 raise ValueError, 'invalid ip address %s' % value 263 264 return (int(bytes[0]) << 24) | (int(bytes[1]) << 16) | \ 265 (int(bytes[2]) << 8) | (int(bytes[3]) << 0) 266 267def toIpNetmask(value): 268 if not isinstance(value, str): 269 raise TypeError, "wrong type '%s' should be str" % type(value) 270 271 (ip, netmask) = value.split('/') 272 ip = toIpAddress(ip) 273 netmaskParts = netmask.split('.') 274 if len(netmaskParts) == 1: 275 if not 0 <= int(netmask) <= 32: 276 raise ValueError, 'invalid netmask %s' % netmask 277 return (ip, int(netmask)) 278 elif len(netmaskParts) == 4: 279 netmaskNum = toIpAddress(netmask) 280 if netmaskNum == 0: 281 return (ip, 0) 282 testVal = 0 283 for i in range(32): 284 testVal |= (1 << (31 - i)) 285 if testVal == netmaskNum: 286 return (ip, i + 1) 287 raise ValueError, 'invalid netmask %s' % netmask 288 else: 289 raise ValueError, 'invalid netmask %s' % netmask 290 291def toIpWithPort(value): 292 if not isinstance(value, str): 293 raise TypeError, "wrong type '%s' should be str" % type(value) 294 295 (ip, port) = value.split(':') 296 ip = toIpAddress(ip) 297 if not 0 <= int(port) <= 0xffff: 298 raise ValueError, 'invalid port %s' % port 299 return (ip, int(port)) |