Last active
April 16, 2022 19:57
-
-
Save serg06/62003559872199a0bfcfb7e42341a256 to your computer and use it in GitHub Desktop.
[Python] Get all IPs in a range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.