python网络编程(3)

来源:互联网 发布:淘宝店铺页面怎么设计 编辑:程序博客网 时间:2024/06/05 19:34

python网络编程

将ipv4地址转换成不同格式:

import socketimport binasciidef convert_ipv4_address():    ipv4 = ['127.0.0.1','192.168.1.1']    for each in ipv4:        packed_ip_addr = socket.inet_aton(each)        unpacked_ip_addr = socket.inet_ntoa(packed_ip_addr)        print ("Ipv4: %s ===>  Packed :%s" % (each,binascii.hexlify(packed_ip_addr)))        print ("Packed : %s ===> Unpacked : %s" % (binascii.hexlify(packed_ip_addr),unpacked_ip_addr))if __name__ == '__main__':        convert_ipv4_address()

packed_ip = socket.inet_aton(ip_address)
ip_address = socket.inet_ntoa(packed_ip)
ip地址不同格式转换函数

python手册查询:

socket.inet_aton(ip_string) :Convert an IPv4 address from dotted-quad string format (for example, ‘123.45.67.89’) to 32-bit packed binary format, as a bytes object four characters in length. ***This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary this function returns.***inet_aton() also accepts strings with less than three dots; see the Unix manual page inet(3) for details.If the IPv4 address string passed to this function is invalid, OSError will be raised. Note that exactly what is valid depends on the underlying C implementation of inet_aton().inet_aton() does not support IPv6, and inet_pton() should be used instead for IPv4/v6 dual stack support.socket.inet_ntoa(packed_ip) :Convert a 32-bit packed IPv4 address (a bytes object four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’). ***This is useful when conversing with a program that uses the standard C library and needs objects of type struct in_addr, which is the C type for the 32-bit packed binary data this function takes as an argument.***If the byte sequence passed to this function is not exactly 4 bytes in length, OSError will be raised. inet_ntoa() does not support IPv6, and inet_ntop() should be used instead for IPv4/v6 dual stack support.

以上代码导入的库  dinascii    Convert between binary and ASCII

binascii.hexlify(data)  返回二进制的十六进制表示

>>>import binascii>>>a  = binascii.hexlify(b'61hello')>>>ab'363168656c6c6f'

binascii.unhexlify(data)

>>>binascii.unhexlify(a)b'61hello'

查看dinascii库

0 0