gpt4 book ai didi

python - 从 IP 字符串转换为整数,并在 Python 中向后转换

转载 作者:IT老高 更新时间:2023-10-28 21:33:45 26 4
gpt4 key购买 nike

我的脚本有点问题,我需要将'xxx.xxx.xxx.xxx'形式的ip转换为整数表示,然后从这种形式返回。

def iptoint(ip):
return int(socket.inet_aton(ip).encode('hex'),16)

def inttoip(ip):
return socket.inet_ntoa(hex(ip)[2:].decode('hex'))


In [65]: inttoip(iptoint('192.168.1.1'))
Out[65]: '192.168.1.1'

In [66]: inttoip(iptoint('4.1.75.131'))
---------------------------------------------------------------------------
error Traceback (most recent call last)

/home/thc/<ipython console> in <module>()

/home/thc/<ipython console> in inttoip(ip)

error: packed IP wrong length for inet_ntoa`

有人知道怎么解决吗?

最佳答案

#!/usr/bin/env python
import socket
import struct


def ip2int(addr):
return struct.unpack("!I", socket.inet_aton(addr))[0]


def int2ip(addr):
return socket.inet_ntoa(struct.pack("!I", addr))


print(int2ip(0xc0a80164)) # 192.168.1.100
print(ip2int('10.0.0.1')) # 167772161

关于python - 从 IP 字符串转换为整数,并在 Python 中向后转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5619685/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com