IP地址与Bigint转换

By | 2012/09/03

这个程序主要是描述转换思路,Python已经对转换进行了封装,直接调用即可。

 

import sys

def ipToBigint(ipaddr):
    ipStrs = ipaddr.split(".")

    return str(int(ipStrs[3]) + int(ipStrs[2])*256 + int(ipStrs[1])*256*256 + int(ipStrs[0])*256*256*256)

def bigintToIp(intStr):
    bigint = int(intStr)

    first = bigint/(256*256*256)
    rest = bigint - (first*256*256*256)

    second = rest/(256*256)
    rest -= second*256*256

    third = rest/256
    fourth = rest - third * 256

    return "%d.%d.%d.%d"%(first,second,third,fourth)

if __name__ == "__main__":
    while 1:
        if len(sys.argv) > 1:
            ipOrInt = sys.argv[1]
        else:
            ipOrInt = raw_input("Please input the IP/Int ->")

        if ipOrInt.find(".") > 0 :
            print "%s <-> %s"%(ipOrInt,ipToBigint(ipOrInt))
        else:
            print "%s <-> %s"%(ipOrInt,bigintToIp(ipOrInt))

 

 

运行截图
iptobigint

Leave a Reply

Your email address will not be published. Required fields are marked *