Convert an IP string to a number and vice versa

前端 未结 9 983
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 03:01

How would I use python to convert an IP address that comes as a str to a decimal number and vice versa?

For example, for the IP 186.99.109.000 &l

相关标签:
9条回答
  • 2020-11-28 04:00

    Use class IPAddress in module netaddr.

    ipv4 str -> int:

    print int(netaddr.IPAddress('192.168.4.54'))
    # OUTPUT: 3232236598
    

    ipv4 int -> str:

    print str(netaddr.IPAddress(3232236598))
    # OUTPUT: 192.168.4.54
    

    ipv6 str -> int:

    print int(netaddr.IPAddress('2001:0db8:0000:0000:0000:ff00:0042:8329'))
    # OUTPUT: 42540766411282592856904265327123268393
    

    ipv6 int -> str:

    print str(netaddr.IPAddress(42540766411282592856904265327123268393))
    # OUTPUT: 2001:db8::ff00:42:8329
    
    0 讨论(0)
  • 2020-11-28 04:00

    Since Python 3.3 there is the ipaddress module that does exactly this job among others: https://docs.python.org/3/library/ipaddress.html. Backports for Python 2.x are also available on PyPI.

    Example usage:

    import ipaddress
    
    ip_in_int = int(ipaddress.ip_address('192.168.1.1'))
    ip_in_hex = hex(ipaddress.ip_address('192.168.1.1'))
    
    0 讨论(0)
  • 2020-11-28 04:04

    Convert IP to integer :

    python -c "print sum( [int(i)*2**(8*j) for  i,j in zip( '10.20.30.40'.split('.'), [3,2,1,0]) ] )"
    

    Convert Interger to IP :

    python -c "print '.'.join( [ str((169090600 >> 8*i) % 256)  for i in [3,2,1,0] ])" 
    
    0 讨论(0)
提交回复
热议问题