python的数字IP实现

第一种方法:

    import socket, struct

    >>> def ip2num(ip):
    ...     return struct.unpack("!L", socket.inet_aton(ip))[0]
    ...
    >>> ip2num('1.1.1.1')
    16843009
    >>> socket.inet_ntoa(struct.pack('!L', 16843009))
    '1.1.1.1'


第二种方法:

    >>> import ipaddress
    >>> int(ipaddress.IPv4Address('1.1.1.1'))
    16843009
    >>> ipaddress.IPv4Address(16843009)
    IPv4Address('1.1.1.1')
  >>> str(ipaddress.IPv4Address('1.1.1.1'))
  '1.1.1.1'
  >>> ipaddress.ip_address(16843009)
  IPv4Address('1.1.1.1')

   ipaddress也是和socket模块交互,需要使用到int和str的内置函数

 

算法:1*256*256*256 + 1* 256*256 + 1*256 +1

用途:

  当存储IPv4地址时,应该使用32位的无符号整数(UNSIGNED INT)来存储IP地址,而不是使用字符串

    优点:

      节省空间

      便于使用范围查询且效率更高

    缺点:

      因为需要转换,不利于阅读

posted @ 2018-10-16 16:01  丁壮  阅读(442)  评论(0编辑  收藏  举报