Parse a string and return the corresponding IP address (as integer) and a guess of the IP version. Following address formats are recognized: >>> def testParseAddress(address): ... ip, version = parseAddress(address) ... print(("%s (IPv%s)" % (ip, version))) ...
(ipstr, ipversion=0)
| 1339 | |
| 1340 | |
| 1341 | def parseAddress(ipstr, ipversion=0): |
| 1342 | """ |
| 1343 | Parse a string and return the corresponding IP address (as integer) |
| 1344 | and a guess of the IP version. |
| 1345 | |
| 1346 | Following address formats are recognized: |
| 1347 | |
| 1348 | >>> def testParseAddress(address): |
| 1349 | ... ip, version = parseAddress(address) |
| 1350 | ... print(("%s (IPv%s)" % (ip, version))) |
| 1351 | ... |
| 1352 | >>> testParseAddress('0x0123456789abcdef') # IPv4 if <= 0xffffffff else IPv6 |
| 1353 | 81985529216486895 (IPv6) |
| 1354 | >>> testParseAddress('123.123.123.123') # IPv4 |
| 1355 | 2071690107 (IPv4) |
| 1356 | >>> testParseAddress('123.123') # 0-padded IPv4 |
| 1357 | 2071658496 (IPv4) |
| 1358 | >>> testParseAddress('127') |
| 1359 | 2130706432 (IPv4) |
| 1360 | >>> testParseAddress('255') |
| 1361 | 4278190080 (IPv4) |
| 1362 | >>> testParseAddress('256') |
| 1363 | 256 (IPv4) |
| 1364 | >>> testParseAddress('108000000000000000080800200C417A') |
| 1365 | 21932261930451111902915077091070067066 (IPv6) |
| 1366 | >>> testParseAddress('0x108000000000000000080800200C417A') |
| 1367 | 21932261930451111902915077091070067066 (IPv6) |
| 1368 | >>> testParseAddress('1080:0000:0000:0000:0008:0800:200C:417A') |
| 1369 | 21932261930451111902915077091070067066 (IPv6) |
| 1370 | >>> testParseAddress('1080:0:0:0:8:800:200C:417A') |
| 1371 | 21932261930451111902915077091070067066 (IPv6) |
| 1372 | >>> testParseAddress('1080:0::8:800:200C:417A') |
| 1373 | 21932261930451111902915077091070067066 (IPv6) |
| 1374 | >>> testParseAddress('::1') |
| 1375 | 1 (IPv6) |
| 1376 | >>> testParseAddress('::') |
| 1377 | 0 (IPv6) |
| 1378 | >>> testParseAddress('0:0:0:0:0:FFFF:129.144.52.38') |
| 1379 | 281472855454758 (IPv6) |
| 1380 | >>> testParseAddress('::13.1.68.3') |
| 1381 | 218186755 (IPv6) |
| 1382 | >>> testParseAddress('::FFFF:129.144.52.38') |
| 1383 | 281472855454758 (IPv6) |
| 1384 | """ |
| 1385 | |
| 1386 | try: |
| 1387 | hexval = int(ipstr, 16) |
| 1388 | except ValueError: |
| 1389 | hexval = None |
| 1390 | try: |
| 1391 | intval = int(ipstr, 10) |
| 1392 | except ValueError: |
| 1393 | intval = None |
| 1394 | |
| 1395 | if ipstr.startswith('0x') and hexval is not None: |
| 1396 | if hexval > MAX_IPV6_ADDRESS: |
| 1397 | raise ValueError("IP Address can't be larger than %x: %x" % (MAX_IPV6_ADDRESS, hexval)) |
| 1398 | if hexval <= MAX_IPV4_ADDRESS: |
no test coverage detected