ipam/cmd/classes.go

80 lines
1.8 KiB
Go
Raw Normal View History

2023-03-14 17:21:49 +01:00
/*
Copyright © 2023 Laura Kalb <dev@lauka.net>
*/
package cmd
import (
2023-03-15 16:43:20 +01:00
"errors"
2023-03-14 17:21:49 +01:00
"net/netip"
2023-03-24 16:27:09 +01:00
"time"
2023-03-14 17:21:49 +01:00
)
type Subnet struct {
2023-03-24 16:27:09 +01:00
Subnet netip.Prefix `json:"subnet"`
Name string `json:"name"`
Vlan string `json:"vlan"`
ChangedAt time.Time `json:"changedat,omitempty"`
ChangedBy string `json:"changedby,omitempty"`
Addresses []Address `json:"addresses"`
2023-03-14 17:21:49 +01:00
}
// HasIP checks if a Subnet already contains given netip.Addr.
// Returns true if the IP already is present, false otherwise.
func (s Subnet) HasIP(ip netip.Addr) bool {
iscontained := false
for _, element := range s.Addresses {
if element.IP.Compare(ip) == 0 {
iscontained = true
}
}
return iscontained
}
2023-03-15 16:43:20 +01:00
// RemoveIP removes the Address object for given ip from
// the Address list of the subnet.
//
// Returns the changed Subnet and nil if delete was
// successful, or an empty Subnet and an error if
// ip could not be deleted.
func (s Subnet) RemoveIP(ip netip.Addr) (Subnet, error) {
var addrlist []Address
if !s.HasIP(ip) {
return Subnet{}, errors.New("IP " + ip.String() + " wasn't found in subnet " + s.Subnet.String())
}
for _, item := range s.Addresses {
if item.IP.Compare(ip) != 0 {
addrlist = append(addrlist, item)
}
}
s.Addresses = addrlist
return s, nil
2023-03-14 17:21:49 +01:00
}
2023-03-15 16:43:20 +01:00
// GetIP returns the Address object for the subnet with
// netip.Addr ip.
//
// Returns the Address object and true if a corresponding
// object was found, an empty Address and false otherwise.
func (s Subnet) GetIP(ip netip.Addr) (Address, bool) {
for _, item := range s.Addresses {
if item.IP.Compare(ip) == 0 {
return item, true
}
}
return Address{}, false
2023-03-14 17:21:49 +01:00
}
type Address struct {
2023-03-24 16:27:09 +01:00
IP netip.Addr `json:"ip"`
FQDN string `json:"fqdn"`
ChangedAt time.Time `json:"changedat,omitempty"`
ChangedBy string `json:"changedby,omitempty"`
2023-03-14 17:21:49 +01:00
}