Filip Tehlar | 3a910ab | 2023-06-08 17:39:39 +0200 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import "fmt" |
| 4 | |
| 5 | type AddressCounter = int |
| 6 | |
| 7 | type Ip4AddressAllocator struct { |
| 8 | networks map[int]AddressCounter |
| 9 | } |
| 10 | |
| 11 | func (a *Ip4AddressAllocator) AddNetwork(networkNumber int) { |
| 12 | a.networks[networkNumber] = 1 |
| 13 | } |
| 14 | |
| 15 | func (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 | |
| 37 | func NewIp4AddressAllocator() *Ip4AddressAllocator { |
| 38 | var ip4AddrAllocator = new(Ip4AddressAllocator) |
| 39 | ip4AddrAllocator.networks = make(map[int]AddressCounter) |
| 40 | ip4AddrAllocator.AddNetwork(0) |
| 41 | return ip4AddrAllocator |
| 42 | } |