python - 以 64 位编码两个 ipv4 地址

标签 python

如果我有一对 IP 地址,例如:

IP1="168.2.65.33"
IP2="192.4.2.55"

我想将每一对编码为 64 位值,以便前 32 位是第一个 IP 地址,第二个是第二个 IP 地址。然后我希望能够将 64 位值保存到一个文件中,以便我可以读回它并恢复这两个 IP 地址。

目的是节省空间。

是否可以在 python 中执行此操作?

最佳答案

不用担心将它们编码为 64 位。 IPv4 地址是 32 位(4 字节)。如果将其中两个写入文件,则文件大小为 8 个字节。

使用socket.inet_aton将人类可读的 IP 地址 string 转换为打包的二进制原始 4 字节字符串:

import socket
ip_addrs = ["168.2.65.33", "192.4.2.55"]

with open('data.out', 'wb') as f:
    for ip in ip_addrs:
        raw = socket.inet_aton(ip)
        f.write(raw)

结果:

$ hexdump -Cv data.out 
00000000  a8 02 41 21 c0 04 02 37                           |..A!...7|
00000008

互补转换函数socket.inet_ntoa会将打包的 4 字节字符串转换回人类可读的 IP 地址。


这是一个写和读回它们的例子:

import socket

ip_pairs = [
    ('1.1.1.1', '1.1.1.2'),
    ('2.2.2.2', '2.2.2.3'),
    ('3.3.3.3', '3.3.3.4'),
]

# Write them out
with open('data.out', 'wb') as f:
    for ip1, ip2 in ip_pairs:
        raw = socket.inet_aton(ip1) + socket.inet_aton(ip2)
        f.write(raw)

def read_with_eof(f, n):
    res = f.read(n)
    if len(res) != n:
        raise EOFError
    return res

# Read them back in
result = []
with open('data.out', 'rb') as f:
    while True:
        try:
            ip1 = socket.inet_ntoa(read_with_eof(f, 4))
            ip2 = socket.inet_ntoa(read_with_eof(f, 4))
            result.append((ip1, ip2))
        except EOFError:
            break

print 'Input:', ip_pairs
print 'Result:', result

输出:

$ python pairs.py 
Input: [('1.1.1.1', '1.1.1.2'), ('2.2.2.2', '2.2.2.3'), ('3.3.3.3', '3.3.3.4')]
Result: [('1.1.1.1', '1.1.1.2'), ('2.2.2.2', '2.2.2.3'), ('3.3.3.3', '3.3.3.4')]

关于python - 以 64 位编码两个 ipv4 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38508422/

相关文章:

python - 将 Async/Await 与 Pickle 结合使用

python - 冲突的 OpenCV 和 Matplotlib

python - 比较其他 Pandas 数据框每一行的值(value)

python - Mac OS X - 环境错误 : mysql_config not found

java - 如何使用 Java 加密消息,然后使用 Python 为 AES GCM 算法解密消息

python - 生成测试数据 - 如何为给定的美国邮政编码生成有效地址?

python - 正在解决试图在 DataFrame 的切片副本上设置值

python - 从 Python 中的不安全用户输入评估数学方程

python - 在 Python 中更简洁地表示规则 (if-else)

python - python中的联合平均实现