GetIP returns an IP address within the allocated subnet for a given host suffix. It reserves the last octet for the requested suffix, so callers should use small host numbers such as 2, 10, 100, etc.
(subnet string, suffix int)
| 62 | // It reserves the last octet for the requested suffix, so callers should use small |
| 63 | // host numbers such as 2, 10, 100, etc. |
| 64 | func GetIP(subnet string, suffix int) string { |
| 65 | prefix, err := netip.ParsePrefix(subnet) |
| 66 | if err != nil { |
| 67 | panic(fmt.Sprintf("invalid subnet format: %s", subnet)) |
| 68 | } |
| 69 | |
| 70 | addr := prefix.Addr() |
| 71 | if !addr.Is4() { |
| 72 | panic(fmt.Sprintf("unsupported non-IPv4 subnet: %s", subnet)) |
| 73 | } |
| 74 | |
| 75 | bytes := addr.As4() |
| 76 | bytes[3] = byte(suffix) |
| 77 | ip := netip.AddrFrom4(bytes) |
| 78 | if !prefix.Contains(ip) { |
| 79 | panic(fmt.Sprintf("requested IP %s is outside subnet %s", ip, subnet)) |
| 80 | } |
| 81 | return ip.String() |
| 82 | } |