Skip to content

Instantly share code, notes, and snippets.

@serg06
Last active April 16, 2022 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serg06/62003559872199a0bfcfb7e42341a256 to your computer and use it in GitHub Desktop.
Save serg06/62003559872199a0bfcfb7e42341a256 to your computer and use it in GitHub Desktop.
[Python] Get all IPs in a range
import itertools as it
"""
Given a start/end IP, return all IPs in that range (inclusive)
"""
def ipRange(start_ip: str, end_ip: str):
start = [int(x) for x in start_ip.split('.')]
end = [int(x) for x in end_ip.split('.')]
yield start_ip
# Work on one section at a time, starting from the end
for part in reversed(range(1, len(end))):
for ip in it.product(
*[[x] for x in start[:part]], # Any previous sections only have one option, e.g. (192.168).*.*
range(start[part] + 1, end[part] + 1), # The current section must be in the range in the start/end IPs
*[range(256) for _ in start[part+1:]] # The remaining sections can be anything 0-255
):
yield '.'.join(map(str, ip))
@serg06
Copy link
Author

serg06 commented Apr 16, 2022

I think I might have copied over an error from the original code.

It seems that the range "192.168.0.1", "192.168.2.1" will not include "192.168.0.2", but will include "192.168.2.2", which both seem to be wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment