How can I loop through an IP address range in python

前端 未结 5 1777
一向
一向 2020-12-16 02:55

How can I loop through an IP address range in python? Lets say I want to loop through every IP from 192.168.1.1 to 192.168. How can this be done?

5条回答
  •  离开以前
    2020-12-16 03:22

    If you want to loop through a network you can define a network using ipaddress module. Such as ipaddress.IPv4Network('192.168.1.0/24')

    import ipaddress
    for ip in ipaddress.IPv4Network('192.168.1.0/24'):
        print(ip)
    

    This will produce a result like this:

    192.168.1.0
    192.168.1.1
    192.168.1.2
    192.168.1.3
    ...
    192.168.1.255
    

    But if you want to iterate through a range of ip's, you might need to convert between ip and integer.

    >>> int(ipaddress.IPv4Address('10.0.0.1'))
    167772161
    

    So:

    start_ip = ipaddress.IPv4Address('10.0.0.1')
    end_ip = ipaddress.IPv4Address('10.0.0.5')
    for ip_int in range(int(start_ip), int(end_ip)):
        print(ipaddress.IPv4Address(ip_int))
    

    will produce a result like:

    10.0.0.1
    10.0.0.2
    10.0.0.3
    10.0.0.4
    

提交回复
热议问题