我想使用所有可打印字符将IP地址编码为尽可能短的字符串.根据https://en.wikipedia.org/wiki/ASCII#Printable_characters,这些是代码20hex到7Ehex.
例如:
shorten("172.45.1.33") --> "^.1 9" maybe.
Run Code Online (Sandbox Code Playgroud)
为了使解码变得容易,我还需要编码的长度始终相同.我还想避免使用空格字符以便将来更容易解析.
怎么能这样做?
我正在寻找一个适用于Python 2.7.x的解决方案.
到目前为止,我尝试修改Eloims在Python 2中的工作答案:
首先,我为Python 2安装了ipaddress backport(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"))
Run Code Online (Sandbox Code Playgroud)
这现在失败了,因为base64没有属性'a85encode'.
以二进制存储的IP是4个字节.
您可以使用Base85将其编码为5个可打印的ASCII字符.
使用更多可打印字符将无法缩短生成的字符串.
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"))
Run Code Online (Sandbox Code Playgroud)
我发现这个问题正在寻找一种在 python 2 上使用 base85/ascii85 的方法。最终我发现了几个可以通过 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"))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
551 次 |
| 最近记录: |