如果我有一对 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/