Created
March 26, 2026 21:42
-
-
Save ZavierChambers/130b1e6e5e65a58098bd17859200d3c9 to your computer and use it in GitHub Desktop.
This lets you generate an IPv4
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 random | |
| import ipaddress | |
| # ------------------------------- | |
| # BUILT-IN EXCLUDED RANGES (IANA + Reserved) | |
| # ------------------------------- | |
| EXCLUDED_CIDRS = [ | |
| "0.0.0.0/8", | |
| "10.0.0.0/8", | |
| "100.64.0.0/10", | |
| "127.0.0.0/8", | |
| "169.254.0.0/16", | |
| "172.16.0.0/12", | |
| "192.0.0.0/24", | |
| "192.0.2.0/24", | |
| "192.88.99.0/24", | |
| "192.168.0.0/16", | |
| "198.18.0.0/15", | |
| "198.51.100.0/24", | |
| "203.0.113.0/24", | |
| "224.0.0.0/4", | |
| "240.0.0.0/4", | |
| "255.255.255.255/32" | |
| ] | |
| # Convert to network objects once | |
| EXCLUDED_NETWORKS = [ipaddress.ip_network(cidr) for cidr in EXCLUDED_CIDRS] | |
| # ------------------------------- | |
| # LOAD OPTIONAL OPT-OUT LIST | |
| # ------------------------------- | |
| def load_opt_out_ranges(file_path="opt_out_ranges.txt"): | |
| networks = [] | |
| try: | |
| with open(file_path, "r") as f: | |
| for line in f: | |
| line = line.strip() | |
| if line and not line.startswith("#"): | |
| networks.append(ipaddress.ip_network(line)) | |
| except FileNotFoundError: | |
| pass # No opt-out file is fine | |
| return networks | |
| OPT_OUT_NETWORKS = load_opt_out_ranges() | |
| # ------------------------------- | |
| # CHECK IF IP IS ALLOWED | |
| # ------------------------------- | |
| def is_allowed(ip): | |
| for net in EXCLUDED_NETWORKS: | |
| if ip in net: | |
| return False | |
| for net in OPT_OUT_NETWORKS: | |
| if ip in net: | |
| return False | |
| return True | |
| # ------------------------------- | |
| # GENERATE RANDOM PUBLIC IP | |
| # ------------------------------- | |
| def generate_random_ip(): | |
| while True: | |
| # Generate random 32-bit integer | |
| ip_int = random.randint(0, 2**32 - 1) | |
| ip = ipaddress.IPv4Address(ip_int) | |
| if is_allowed(ip): | |
| return str(ip) | |
| # ------------------------------- | |
| # MAIN EXECUTION | |
| # ------------------------------- | |
| if __name__ == "__main__": | |
| print("Random Allowed IPv4 Addresses:\n") | |
| for _ in range(10): | |
| print(generate_random_ip()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment