Conversion from IP string to integer, and backward in Python

后端 未结 11 870
囚心锁ツ
囚心锁ツ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 22:54

    I used following:

    ip2int = lambda ip: reduce(lambda a,b: long(a)*256 + long(b), ip.split('.'))
    
    ip2int('192.168.1.1')
    
    #output
    
    3232235777L
    
    # from int to ip
    int2ip = lambda num: '.'.join( [ str((num >> 8*i) % 256)  for i in [3,2,1,0] ])
    
    int2ip(3232235777L)
    
    #output
    
    '192.168.1.1'
    

提交回复
热议问题