14

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?

2
  • 2
    is 192.168. a valid ip address? Commented Nov 13, 2012 at 20:59
  • have a look at the IPy library Commented Nov 13, 2012 at 21:01

5 Answers 5

26

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
Sign up to request clarification or add additional context in comments.

Comments

5

You can use itertools.product:

for i,j in product(range(256),range(256)):
    print "192.168.{0}.{1}".format(i,j)

Comments

4

Did you try, you know, looping with range?

for i in range(256):
    for j in range(256):
        ip = "192.168.%d.%d" % (i, j)
        print ip

Comments

3
from netaddr import *
ip = IPNetwork('192.0.2.16/29')
>>> ip_list = list(ip)
>>> len(ip_list)
8
>>> ip_list
[IPAddress('192.0.2.16'), IPAddress('192.0.2.17'), ..., IPAddress('192.0.2.22'), IPAddress('192.0.2.23')]

2 Comments

Hi Petr - your answer would be better if you could include some explanation of how or why your code would solve the questioner's problem.
Hi Petr, thanks for this solution, it was exactly what I was looking for as I am already using netaddr and I don't want to import another lib
2

Using netaddr module: http://netaddr.readthedocs.io/en/latest/api.html#netaddr.IPSet.iter_ipranges

from netaddr import iter_iprange
generator = iter_iprange('192.168.1.1', '192.168.255.255', step=1)
generator.next() # 192.168.1.1
generator.next() # 192.168.1.2

1 Comment

link is broken.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.