Conversion from IP string to integer, and backward in Python

后端 未结 11 868
囚心锁ツ
囚心锁ツ 2020-12-07 22:34

i have a little problem with my script, where i need to convert ip in form \'xxx.xxx.xxx.xxx\' to integer representation and go back from this form.

def ipto         


        
11条回答
  •  醉酒成梦
    2020-12-07 22:50

    Let me give a more understandable way:

    ip to int

    def str_ip2_int(s_ip='192.168.1.100'):
        lst = [int(item) for item in s_ip.split('.')]
        print lst   
        # [192, 168, 1, 100]
    
        int_ip = lst[3] | lst[2] << 8 | lst[1] << 16 | lst[0] << 24
        return int_ip   # 3232235876
    

    The above:

    lst = [int(item) for item in s_ip.split('.')]
    

    equivalent to :

    lst = map(int, s_ip.split('.'))
    

    also:

    int_ip = lst[3] | lst[2] << 8 | lst[1] << 16 | lst[0] << 24
    

    equivalent to :

    int_ip = lst[3] + (lst[2] << 8) + (lst[1] << 16) + (lst[0] << 24)
    
    int_ip = lst[3] + lst[2] * pow(2, 8) + lst[1] * pow(2, 16) + lst[0] * pow(2, 24)
    

    int to ip:

    def int_ip2str(int_ip=3232235876):
        a0 = str(int_ip & 0xff)
        a1 = str((int_ip & 0xff00) >> 8) 
        a2 = str((int_ip & 0xff0000) >> 16)
        a3 = str((int_ip & 0xff000000) >> 24)
    
        return ".".join([a3, a2, a1, a0])
    

    or:

    def int_ip2str(int_ip=3232235876):
        lst = []
        for i in xrange(4):
            shift_n = 8 * i
            lst.insert(0, str((int_ip >> shift_n) & 0xff))
    
        return ".".join(lst)
    

提交回复
热议问题