Allow link argument to AddrAdd, AddReplace and AddrDel to be nil

This commit is contained in:
Christian Worm Mortensen 2024-01-31 22:26:27 +01:00 committed by Alessandro Boch
parent 0cd15d9a7a
commit 70def89fcb
2 changed files with 58 additions and 49 deletions

View File

@ -74,17 +74,19 @@ func (h *Handle) AddrDel(link Link, addr *Addr) error {
}
func (h *Handle) addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error {
family := nl.GetIPFamily(addr.IP)
msg := nl.NewIfAddrmsg(family)
msg.Scope = uint8(addr.Scope)
if link == nil {
msg.Index = uint32(addr.LinkIndex)
} else {
base := link.Attrs()
if addr.Label != "" && !strings.HasPrefix(addr.Label, base.Name) {
return fmt.Errorf("label must begin with interface name")
}
h.ensureIndex(base)
family := nl.GetIPFamily(addr.IP)
msg := nl.NewIfAddrmsg(family)
msg.Index = uint32(base.Index)
msg.Scope = uint8(addr.Scope)
}
mask := addr.Mask
if addr.Peer != nil {
mask = addr.Peer.Mask

View File

@ -145,6 +145,7 @@ func TestAddrAddReplace(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
for _, nilLink := range []bool{false, true} {
var address = &net.IPNet{IP: net.IPv4(127, 0, 0, 2), Mask: net.CIDRMask(24, 32)}
var addr = &Addr{IPNet: address}
@ -153,6 +154,11 @@ func TestAddrAddReplace(t *testing.T) {
t.Fatal(err)
}
if nilLink {
addr.LinkIndex = link.Attrs().Index
link = nil
}
err = AddrAdd(link, addr)
if err != nil {
t.Fatal(err)
@ -198,6 +204,7 @@ func TestAddrAddReplace(t *testing.T) {
if len(addrs) != 0 {
t.Fatal("Address not removed properly")
}
}
}
func expectAddrUpdate(ch <-chan AddrUpdate, add bool, dst net.IP) bool {