blob: c08f88958dc1dd531af9f1695cb28782643ab978 [file] [log] [blame]
Filip Tehlar3a910ab2023-06-08 17:39:39 +02001package main
2
3import "fmt"
4
5type AddressCounter = int
6
7type Ip4AddressAllocator struct {
8 networks map[int]AddressCounter
9}
10
11func (a *Ip4AddressAllocator) AddNetwork(networkNumber int) {
12 a.networks[networkNumber] = 1
13}
14
15func (a *Ip4AddressAllocator) NewIp4InterfaceAddress(inputNetworkNumber ...int) (string, error) {
16 var networkNumber int = 0
17 if len(inputNetworkNumber) > 0 {
18 networkNumber = inputNetworkNumber[0]
19 }
20
21 if _, ok := a.networks[networkNumber]; !ok {
22 a.AddNetwork(networkNumber)
23 }
24
25 numberOfAddresses := a.networks[networkNumber]
26
27 if numberOfAddresses == 254 {
28 return "", fmt.Errorf("no available IPv4 addresses")
29 }
30
31 address := fmt.Sprintf("10.10.%v.%v/24", networkNumber, numberOfAddresses)
32 a.networks[networkNumber] = numberOfAddresses + 1
33
34 return address, nil
35}
36
37func NewIp4AddressAllocator() *Ip4AddressAllocator {
38 var ip4AddrAllocator = new(Ip4AddressAllocator)
39 ip4AddrAllocator.networks = make(map[int]AddressCounter)
40 ip4AddrAllocator.AddNetwork(0)
41 return ip4AddrAllocator
42}