|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# Usage: |
| 4 | +# fetch_nth_ip.py <subnet> <offset> |
| 5 | + |
| 6 | +# For example: |
| 7 | +# fetch_nth_ip.py 192.168.1.0/24 0 returns 192.168.1.1 |
| 8 | +# fetch_nth_ip.py 2001:db8::/64 0 returns 2001:db8::1 |
| 9 | +# fetch_nth_ip.py 192.168.1.0/24 10 returns 192.168.1.11 |
| 10 | +# fetch_nth_ip.py 2001:db8::/64 10 returns 2001:db8::b |
| 11 | + |
| 12 | +import sys |
| 13 | +import argparse |
| 14 | +import ipaddress |
| 15 | + |
| 16 | +def fetch_nth_address(network_str, offset): |
| 17 | + net = ipaddress.ip_network(network_str, strict=False) |
| 18 | + assert offset >= 0, "Offset must be non-negative" |
| 19 | + |
| 20 | + if isinstance(net, ipaddress.IPv4Network): |
| 21 | + if net.prefixlen == 32: |
| 22 | + assert offset == 0, "Offset out of range for single-address subnet." |
| 23 | + return net.network_address |
| 24 | + if net.prefixlen == 31: |
| 25 | + assert offset < 2, "Offset out of range for two-address subnet." |
| 26 | + return ipaddress.ip_address(int(net.network_address) + offset) |
| 27 | + # Regular IPv4: skip network and broadcast |
| 28 | + usable = net.num_addresses - 2 |
| 29 | + assert offset < usable, f"Offset out of range. Usable range: 0 to {usable-1}" |
| 30 | + return ipaddress.ip_address(int(net.network_address) + 1 + offset) |
| 31 | + |
| 32 | + if net.prefixlen == 128: # IPv6 |
| 33 | + assert offset == 0, "Offset out of range for single-address subnet." |
| 34 | + return net.network_address |
| 35 | + |
| 36 | + # Skip the base address by default |
| 37 | + usable = net.num_addresses - 1 |
| 38 | + assert offset < usable, f"Offset out of range. Usable range: 0 to {usable-1}" |
| 39 | + return ipaddress.ip_address(int(net.network_address) + 1 + offset) |
| 40 | + |
| 41 | +if __name__ == "__main__": |
| 42 | + ap = argparse.ArgumentParser(description="Return the Nth address from a network.") |
| 43 | + ap.add_argument("subnet", help="Network in CIDR notation, e.g. 192.168.1.0/24 or 2001:db8::/64") |
| 44 | + ap.add_argument("offset", type=int, help="Offset from the first address") |
| 45 | + args = ap.parse_args() |
| 46 | + try: |
| 47 | + ip = fetch_nth_address(args.subnet, args.offset) |
| 48 | + print(str(ip)) |
| 49 | + except Exception as e: |
| 50 | + print(f"ERROR: {e}", file=sys.stderr) |
| 51 | + sys.exit(1) |
0 commit comments