python实现将IP地址转换为数字

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实现将IP地址转换为数字相关的知识,希望对你有一定的参考价值。

话不多说,直接代码

ip_addr=192.168.2.10

# transfer ip to int
def ip2long(ip):
    ip_list=ip.split(.)
    result=0
    for i in range(4):  #0,1,2,3
        result=result+int(ip_list[i])*256**(3-i)
    return result


long=3232236042

# transfer int to ip
def long2ip(long):
    floor_list=[]
    yushu=long
    for i in reversed(range(4)):   #3,2,1,0
        res=divmod(yushu,256**i)
        floor_list.append(str(res[0]))
        yushu=res[1]
    return ..join(floor_list)



a=long2ip(long)
print(a)

 

以上是关于python实现将IP地址转换为数字的主要内容,如果未能解决你的问题,请参考以下文章