第一种方法:

    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地址,而不是使用字符串

    优点:

      节省空间

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

    缺点:

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

相关文章:

  • 2021-06-19
  • 2022-12-23
  • 2023-02-13
  • 2022-12-23
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-01
  • 2022-12-23
  • 2021-05-02
  • 2021-08-22
相关资源
相似解决方案