if have pairs of ip addresses like:
ip1="168.2.65.33" ip2="192.4.2.55"
i encode each pair 64 bit value first 32 bits first ip address , second second ip address. able save 64 bit value file in such way can read in , recover 2 ip addresses.
the aim save space.
is possible in python?
don't worry encoding them in 64 bits. ipv4 address 32 bits (4 bytes). if write 2 of them file, 8 bytes in size.
use socket.inet_aton
convert human-readable ip address string packed binary raw 4-byte string:
import socket ip_addrs = ["168.2.65.33", "192.4.2.55"] open('data.out', 'wb') f: ip in ip_addrs: raw = socket.inet_aton(ip) f.write(raw)
result:
$ hexdump -cv data.out 00000000 a8 02 41 21 c0 04 02 37 |..a!...7| 00000008
the complementary conversion function socket.inet_ntoa
convert packed 4-byte string human-readable ip address.
here's example of writing , reading them back:
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 open('data.out', 'wb') f: 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 in result = [] open('data.out', 'rb') 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
output:
$ 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')]
Comments
Post a Comment