netlink: add func AddrSubscribe on linux

This commit is contained in:
rkonfj
2024-07-19 19:53:42 +08:00
parent 6c1e81cb3b
commit f1574b7be1
2 changed files with 43 additions and 0 deletions

12
netlink/addr_default.go Normal file
View File

@@ -0,0 +1,12 @@
//go:build !linux && !windows && !darwin
package netlink
import (
"context"
"errors"
)
func AddrSubscribe(ctx context.Context, ch chan<- AddrUpdate) error {
return errors.ErrUnsupported
}

31
netlink/addr_linux.go Normal file
View File

@@ -0,0 +1,31 @@
package netlink
import (
"context"
"github.com/vishvananda/netlink"
)
func AddrSubscribe(ctx context.Context, ch chan<- AddrUpdate) error {
rawChan := make(chan netlink.AddrUpdate)
err := netlink.AddrSubscribe(rawChan, ctx.Done())
if err != nil {
return err
}
go func() {
defer close(ch)
for {
select {
case <-ctx.Done():
return
case e := <-rawChan:
ch <- AddrUpdate{
New: e.NewAddr,
Addr: e.LinkAddress,
LinkIndex: e.LinkIndex,
}
}
}
}()
return nil
}