python网络编程(3)

python网络编程

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

import socket
import binascii
def 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')
>>>a
b'363168656c6c6f'

binascii.unhexlify(data)

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

查看dinascii库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值