[python-nl] IPv6 adres decToHex

t spam spam.tee at gmail.com
Sat May 24 19:58:20 CEST 2008


Beste pythonliefhebbers,

Als een beginnend python gebruiker heb ik een vraag die jullie hopelijk
makkelijk kunnen beantwoorden. De onderstaande code converteert een ipv6
adres in decimal notatie om naar hex. Op de cli geef ik het volgende in:

python decToHex.py 32.1.6.16.15.2.1.32.0.0.0.0.0.0.1.34

waarop ik dit verwacht:

2001:610:f02:120:0:0:0:122

Echter ik krijg dit:

2001:610:f02:120:0:0:0:122None

Waar komt die None vandaan? Ik dacht in eerste instantie dat het de waarde
in array_ip[15] was maar dit is het niet. Hebben jullie een idee?

Bedankt alvast!


Groeten Tijmen

import string
import sys

def printIPv6(ip):
        array_ip = ip.split('.')
        ipv6_tuple = []
        for i in array_ip:
                ipv6_tuple.append(hex(int(i))[2:])

        i = 0
        while i < 14:
                sys.stdout.write(decToHex(array_ip[i], array_ip[i+1]) + ":")
                i = i+2
        sys.stdout.write(decToHex(array_ip[14], array_ip[15]))

def toHex(i):
        """Convert an int into a hex string (without the leading 0x)"""
        return hex(i)[2:]

def decToHex(a, b):
        if int(a) + int(b) == 0:
                return toHex(int(a))
        elif (int(b)) < 10:
                return toHex(int(a)) + "0" + toHex(int(b))
        else:
                return toHex(int(a)) + toHex(int(b))

print printIPv6(sys.argv[1])
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-nl/attachments/20080524/4b820fea/attachment.htm>


More information about the Python-nl mailing list