Encode IP address using all printable characters in Python 2.7.x

I would like to encode the IP address as short a line as possible using all printable characters. According to https://en.wikipedia.org/wiki/ASCII#Printable_characters , these are codes from 20hex to 7Ehex.

For instance:

shorten("172.45.1.33") --> "^.1 9" maybe.

To simplify decoding, I also need the encoding length to always be the same. I would also like to avoid using the space character to simplify parsing in the future.

How can I do that?

I am looking for a solution that works in Python 2.7.x.


My attempt so far to change Eloims to respond to work in Python 2:

First I installed backport for ipaddress for Python 2 ( https://pypi.python.org/pypi/ipaddress ).

#This is needed because ipaddress expects character strings and not byte strings for textual IP address representations 
from __future__ import unicode_literals
import ipaddress
import base64

#Taken from http://stackoverflow.com/a/20793663/2179021
def to_bytes(n, length, endianess='big'):
    h = '%x' % n
    s = ('0'*(len(h) % 2) + h).zfill(length*2).decode('hex')
    return s if endianess == 'big' else s[::-1]

def def encode(ip):
    ip_as_integer = int(ipaddress.IPv4Address(ip))
    ip_as_bytes = to_bytes(ip_as_integer, 4, endianess="big")
    ip_base85 = base64.a85encode(ip_as_bytes)
    return ip_base

print(encode("192.168.0.1"))

, base64 'a85encode'.

+4
2

, base85/ascii85 python 2. , pypi. hackercodecs, /, , ,

from __future__ import unicode_literals
import ipaddress
from hackercodecs import ascii85_encode

def encode(ip):
    return ascii85_encode(ipaddress.ip_address(ip).packed)[0]

print(encode("192.168.0.1"))

+1

IP-, , 4 .

5 ASCII- Base85.

.

import ipaddress
import base64

def encode(ip):
    ip_as_integer = int(ipaddress.IPv4Address(ip))
    ip_as_bytes = ip_as_integer.to_bytes(4, byteorder="big")
    ip_base85 = base64.a85encode(ip_as_bytes)
    return ip_base85

print(encode("192.168.0.1"))
+5

Source: https://habr.com/ru/post/1649375/


All Articles