Convert an IP string to a number and vice versa

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

    converting an IP string to long integer:

    import socket, struct
    
    def ip2long(ip):
        """
        Convert an IP string to long
        """
        packedIP = socket.inet_aton(ip)
        return struct.unpack("!L", packedIP)[0]
    

    the other way around:

    >>> socket.inet_ntoa(struct.pack('!L', 2130706433))
    '127.0.0.1'
    

提交回复
热议问题