diff --git a/pkg/zones/address.go b/pkg/zones/address.go new file mode 100644 index 0000000..187b45a --- /dev/null +++ b/pkg/zones/address.go @@ -0,0 +1,49 @@ +package zones + +import "net/netip" + +// ParseRingZeroAddress extracts zone and node ID from a wg0 [netip.Addr] +func ParseRingZeroAddress(addr netip.Addr) (zoneID int, nodeID int, ok bool) { + if addr.IsValid() { + a4 := addr.As4() + + if a4[0] == 10 && a4[1] == 0 { + return int(a4[2]), int(a4[3]), true + } + } + return 0, 0, false +} + +// RingZeroAddress returns a wg0 IP address +func RingZeroAddress(zoneID, nodeID int) netip.Addr { + c := zoneID + d := nodeID + + return netip.AddrFrom4([4]byte{ + 10, 0, uint8(c), uint8(d), + }) +} + +// ParseRingOneAddress extracts zone and node ID from a wg1 [netip.Addr] +func ParseRingOneAddress(addr netip.Addr) (zoneID int, nodeID int, ok bool) { + if addr.IsValid() { + a4 := addr.As4() + + if a4[0] == 10 && a4[2] == 0 { + zoneID = int(a4[1] >> 4) + nodeID = int(a4[3]) + return zoneID, nodeID, true + } + } + return 0, 0, false +} + +// RingOneAddress returns a wg1 IP address +func RingOneAddress(zoneID, nodeID int) netip.Addr { + b := zoneID << 4 + d := nodeID + + return netip.AddrFrom4([4]byte{ + 10, uint8(b), 0, uint8(d), + }) +}