Convert an IP string to a number and vice versa

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

    Here's One Line Answers:

    import socket, struct
    
    def ip2long_1(ip):
        return struct.unpack("!L", socket.inet_aton(ip))[0]
    

    def ip2long_2(ip):
        return long("".join(["{0:08b}".format(int(num)) for num in ip.split('.')]), 2)
    

    def ip2long_3(ip):
        return long("".join(["{0:08b}".format(num) for num in map(int, ip.split('.'))]), 2)
    

    Execution Times:

    ip2long_1 => 0.0527065660363234 ( The Best )
    ip2long_2 => 0.577211893924598
    ip2long_3 => 0.5552745958088666

提交回复
热议问题