Convert an IP string to a number and vice versa

前端 未结 9 1057
隐瞒了意图╮
隐瞒了意图╮ 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 03:59

    One line solution without any module import:

    ip2int = lambda ip: reduce(lambda a, b: (a << 8) + b, map(int, ip.split('.')), 0)
    int2ip = lambda n: '.'.join([str(n >> (i << 3) & 0xFF) for i in range(0, 4)[::-1]])
    

    Example:

    In [3]: ip2int('121.248.220.85')
    Out[3]: 2046352469
    
    In [4]: int2ip(2046352469)
    Out[4]: '121.248.220.85'
    

提交回复
热议问题