Conversion from IP string to integer, and backward in Python

后端 未结 11 843
囚心锁ツ
囚心锁ツ 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:49

    In pure python without use additional module

    def IP2Int(ip):
        o = map(int, ip.split('.'))
        res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
        return res
    
    
    def Int2IP(ipnum):
        o1 = int(ipnum / 16777216) % 256
        o2 = int(ipnum / 65536) % 256
        o3 = int(ipnum / 256) % 256
        o4 = int(ipnum) % 256
        return '%(o1)s.%(o2)s.%(o3)s.%(o4)s' % locals()
    
    # Example
    print('192.168.0.1 -> %s' % IP2Int('192.168.0.1'))
    print('3232235521 -> %s' % Int2IP(3232235521))
    

    Result:

    192.168.0.1 -> 3232235521
    3232235521 -> 192.168.0.1
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-07 22:50

    My approach is to straightforwardly look at the the number the way it is stored, rather than displayed, and to manipulate it from the display format to the stored format and vice versa.

    So, from an IP address to an int:

    def convertIpToInt(ip):
        return sum([int(ipField) << 8*index for index, ipField in enumerate(reversed(ip.split('.')))])
    

    This evaluates each field, and shifts it to its correct offset, and then sums them all up, neatly converting the IP address' display into its numerical value.

    In the opposite direction, from an int to an IP address:

    def convertIntToIp(ipInt):
        return '.'.join([str(int(ipHexField, 16)) for ipHexField in (map(''.join, zip(*[iter(str(hex(ipInt))[2:].zfill(8))]*2)))])
    

    The numerical representation is first converted into its hexadecimal string representation, which can be manipulated as a sequence, making it easier to break up. Then, pairs are extracted by mapping ''.join onto tuples of pairs provided by zipping a list of two references to an iterator of the IP string (see How does zip(*[iter(s)]*n) work?), and those pairs are in turn converted from hex string representations to int string representations, and joined by '.'.

    0 讨论(0)
  • 2020-12-07 22:53

    It can be done without using any library.

    def iptoint(ip):
            h=list(map(int,ip.split(".")))
            return (h[0]<<24)+(h[0]<<16)+(h[0]<<8)+(h[0]<<0)
    
    def inttoip(ip):
           return ".".join(map(str,[((ip>>24)&0xff),((ip>>16)&0xff),((ip>>8)&0xff),((ip>>0)&0xff)]))
    
    iptoint("8.8.8.8") # 134744072
    
    inttoip(134744072) # 8.8.8.8
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-12-07 22:57

    Python3 oneliner (based on Thomas Webber's Python2 answer):

    sum([int(x) << 8*i for i,x in enumerate(reversed(ip.split('.')))])
    

    Left shifts are much faster than pow().

    0 讨论(0)
提交回复
热议问题