Encode IP address using all printable characters in Python 2.7.x -
i encode ip address in short string possible using printable characters. according https://en.wikipedia.org/wiki/ascii#printable_characters these codes 20hex 7ehex.
for example:
shorten("172.45.1.33") --> "^.1 9" maybe.
in order make decoding easy need length of encoding same. avoid using space character in order make parsing easier in future.
how can 1 this?
i looking solution works in python 2.7.x.
my attempt far modify eloims's answer work in python 2:
first installed ipaddress backport python 2 (https://pypi.python.org/pypi/ipaddress) .
#this needed because ipaddress expects character strings , not byte strings textual ip address representations __future__ import unicode_literals import ipaddress import base64 #taken 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"))
this fails because base64 doesn't have attribute 'a85encode'.
i found question looking way use base85/ascii85 on python 2. discovered couple of projects available install via pypi. settled on 1 called hackercodecs
because project specific encoding/decoding whereas others found offered implementation byproduct of necessity
from __future__ import unicode_literals import ipaddress hackercodecs import ascii85_encode def encode(ip): return ascii85_encode(ipaddress.ip_address(ip).packed)[0] print(encode("192.168.0.1"))
Comments
Post a Comment