python increment ipaddress

后端 未结 8 2105
情话喂你
情话喂你 2020-12-31 09:24

I would like to increment an ip address by a fixed value.

Precisely this is what I am trying to achieve, I have an ip address say, 192.168.0.3 and I wan

相关标签:
8条回答
  • 2020-12-31 10:22

    There's a module that makes this and other tasks very easy: pip install iptools.

    In [1]: import iptools
    
    In [3]: iptools.ip2long('127.0.0.1')
    Out[3]: 2130706433
    
    In [4]: p = iptools.ip2long('127.0.0.1') + 1
    In [6]: iptools.long2ip(p)
    Out[6]: '127.0.0.2'
    
    0 讨论(0)
  • 2020-12-31 10:29

    In Python 3:

    >>> import ipaddress
    >>> ipaddress.ip_address('192.168.0.4')  # accept both IPv4 and IPv6 addresses
    IPv4Address('192.168.0.4')
    >>> int(_)
    3232235524
    
    >>> ipaddress.ip_address('192.168.0.4') + 256
    IPv4Address('192.168.1.4')
    

    In reverse:

    >>> ipaddress.ip_address(3232235524)
    IPv4Address('192.168.0.4')
    >>> str(_)
    '192.168.0.4'
    
    >>> ipaddress.ip_address('192.168.0.4') -1
    IPv4Address('192.168.0.3')
    

    Python 2/3

    You could use struct module to unpack the result of inet_aton() e.g.,

    import struct, socket
    
    # x.x.x.x string -> integer
    ip2int = lambda ipstr: struct.unpack('!I', socket.inet_aton(ipstr))[0]
    print(ip2int("192.168.0.4"))
    # -> 3232235524
    

    In reverse:

    int2ip = lambda n: socket.inet_ntoa(struct.pack('!I', n))
    print(int2ip(3232235525))
    # -> 192.168.0.5
    
    0 讨论(0)
提交回复
热议问题