python 将IP地址转换成打包后的32位格式

 

python 2.7

#!/usr/bin/env python
# Python Network Programming Cookbook -- Chapter - 1
# This program requires Python 2.7 or any later version

import socket
from binascii import hexlify


def convert_ip4_address():
    for ip_addr in ['127.0.0.1', '192.168.0.1']:
        packed_ip_addr = socket.inet_aton(ip_addr)
        unpacked_ip_addr = socket.inet_ntoa(packed_ip_addr)
        print "IP Address: %s => Packed: %s, Unpacked: %s" %(ip_addr, hexlify(packed_ip_addr), unpacked_ip_addr)
    
if __name__ == '__main__':
    convert_ip4_address()

输出

IP Address: 127.0.0.1 => Packed: 7f000001, Unpacked: 127.0.0.1
IP Address: 192.168.0.1 => Packed: c0a80001, Unpacked: 192.168.0.1

 

posted @ 2019-06-16 14:42  anobscureretreat  阅读(388)  评论(0编辑  收藏  举报