python网络编程——将IPv4地址转换成不同的格式

1.将IPv4地址转换为32位二进制格式,用做底层网络函数。

 1 import socket
 2 from binascii import hexlify
 3 
 4 
 5 def convert_IPv4_address():   # 定义convert_IPv4_address()函数
 6     for ip_addr in ['127.0.0.1', '192.168.0.1']:
 7         packed_ip_addr = socket.inet_aton(ip_addr)  # 将对应的IP地址转换为32—bit的封装包
 8         unpacked_ip_addr = socket.inet_ntoa(packed_ip_addr)   # 将对应的32-bit的封装包转换为IP地址的标准点号分隔字符串
 9         print("IP Address: %s => packed: %s, Unpacked: %s" % (ip_addr, hexlify(packed_ip_addr), unpacked_ip_addr))
10 
11 
12 if __name__ == '__main__':
13     convert_IPv4_address()

2. .inet_aton()和inet_ntoa()及hexlify()解释

 1 def inet_aton(string):  # real signature unknown; restored from __doc__
 2     """
 3     inet_aton(string) -> bytes giving packed 32-bit IP representation
 4 
 5     Convert an IP address in string format (123.45.67.89) to the 32-bit packed
 6     binary format used in low-level network functions.
 7     """
 8     return b""
 9     """将ip地址的4段地址分别进行2进制转化,输出用16进制表示
10     >>> import socket
11     >>> from binascii import hexlify
12     >>> a = socket.inet_aton('192.168.1.1')
13     >>> c=  hexlify(a)
14     >>> c
15     b'c0a80101'
16     """
17 
18 
19 
20 def inet_ntoa(packed_ip):  # real signature unknown; restored from __doc__
21     """
22     inet_ntoa(packed_ip) -> ip_address_string
23 
24     Convert an IP address from 32-bit packed binary format to string format
25     """
26     pass
27     """转换32位打包的IPV4地址转换为IP地址的标准点号分隔字符串表示。"""
28 
29 def hexlify(data):  # known case of binascii.hexlify
30     """
31     Hexadecimal representation of binary data.
32 
33     The return value is a bytes object.
34     """
35     return b""
36     """用十六进制形式表示二进制"""

 

posted @ 2016-09-13 23:22  欧阳逸轩  阅读(1586)  评论(0编辑  收藏  举报