Skip to content

Instantly share code, notes, and snippets.

@nmarley
Created September 22, 2016 17:27
Show Gist options
  • Save nmarley/3806818834ef25a965a7a4c526b6a223 to your computer and use it in GitHub Desktop.
Save nmarley/3806818834ef25a965a7a4c526b6a223 to your computer and use it in GitHub Desktop.
IPv6 Shortener in Python
import re
def shorten(ipv6_long):
hextets = ipv6_long.split(':')
temp = []
for hextet in hextets:
# trim leading '0's
hextet = re.sub(r'^0+', '', hextet)
# lowercase any A-F values
hextet = hextet.lower()
if 0 == len(hextet):
hextet = '0'
# append to a temp array
temp.append(hextet)
tempstr = ':'.join(temp)
print "tempstr = %s" % tempstr
ipv6_short = re.sub( r'(:0)+', ':', tempstr, 1 )
return ipv6_short
ipv6_long = '2604:A880:0001:0020:0000:0000:0ECF:2001'
#ipv6_long = '2604:A880:0001:0000:0000:0000:0ECF:2001'
ipv6_short = shorten(ipv6_long)
print "ipv6 (long) = %s" % ipv6_long
print "ipv6 (short) = %s" % ipv6_short
@m-messiah
Copy link

m-messiah commented Jun 18, 2018

There is no needs to use re here:

def shorten_ipv6(ipv6_long):
    hextets = ipv6_long.split(':')
    temp = []
    for hextet in hextets:
        hextet = hextet.lstrip('0').lower()
        if 0 == len(hextet):
            if temp[-1] == '0':
                temp[-1] = ''
                hextet = ''
            else:
                hextet = '0'
        temp.append(hextet)
    return ':'.join(temp)

otherwise, my solution is wrong too - we need to merge zeroes from shortest range, not just from left

@m-messiah
Copy link

solution, based on python3 ipaddress module

def shorten_ipv6(ipv6_long):
    hextets = ['%x' % int(h, 16) for h in ipv6_long.split(':')]
    best_doublecolon_start = -1
    best_doublecolon_len = 0
    doublecolon_start = -1
    doublecolon_len = 0
    for index, hextet in enumerate(hextets):
        if hextet == '0':
            doublecolon_len += 1
            if doublecolon_start == -1:
                # Start of a sequence of zeros.
                doublecolon_start = index
            if doublecolon_len > best_doublecolon_len:
                # This is the longest sequence of zeros so far.
                best_doublecolon_len = doublecolon_len
                best_doublecolon_start = doublecolon_start
        else:
            doublecolon_len = 0
            doublecolon_start = -1
    if best_doublecolon_len > 1:
        best_doublecolon_end = (best_doublecolon_start +
                                best_doublecolon_len)
        # For zeros at the end of the address.
        if best_doublecolon_end == len(hextets):
            hextets += ['']
        hextets[best_doublecolon_start:best_doublecolon_end] = ['']
        # For zeros at the beginning of the address.
        if best_doublecolon_start == 0:
            hextets = [''] + hextets
    return ':'.join(hextets)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment