Add LinkIndex to Addr struct

Currently, it's cumbersome to get a link by an IP addr - one needs to
list all links and then call AddrList() for each of them.

Considering that ifindex is already available to to the parseAddr()
helper function, we can expose it to a user via the newly added
Addr.LinkIndex field. This makes the retrieving link by IP addr much
more simple.

Signed-off-by: Martynas Pumputis <m@lambda.lt>
This commit is contained in:
Martynas Pumputis 2020-06-02 14:44:34 +02:00 committed by Alessandro Boch
parent c79a4b7b40
commit 96dce1cb9f
3 changed files with 12 additions and 7 deletions

View File

@ -17,6 +17,7 @@ type Addr struct {
Broadcast net.IP
PreferedLft int
ValidLft int
LinkIndex int
}
// String returns $ip/$netmask $label

View File

@ -193,12 +193,12 @@ func (h *Handle) AddrList(link Link, family int) ([]Addr, error) {
var res []Addr
for _, m := range msgs {
addr, msgFamily, ifindex, err := parseAddr(m)
addr, msgFamily, err := parseAddr(m)
if err != nil {
return res, err
}
if link != nil && ifindex != indexFilter {
if link != nil && addr.LinkIndex != indexFilter {
// Ignore messages from other interfaces
continue
}
@ -213,11 +213,11 @@ func (h *Handle) AddrList(link Link, family int) ([]Addr, error) {
return res, nil
}
func parseAddr(m []byte) (addr Addr, family, index int, err error) {
func parseAddr(m []byte) (addr Addr, family int, err error) {
msg := nl.DeserializeIfAddrmsg(m)
family = -1
index = -1
addr.LinkIndex = -1
attrs, err1 := nl.ParseRouteAttr(m[msg.Len():])
if err1 != nil {
@ -226,7 +226,7 @@ func parseAddr(m []byte) (addr Addr, family, index int, err error) {
}
family = int(msg.Family)
index = int(msg.Index)
addr.LinkIndex = int(msg.Index)
var local, dst *net.IPNet
for _, attr := range attrs {
@ -391,7 +391,7 @@ func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-c
continue
}
addr, _, ifindex, err := parseAddr(m.Data)
addr, _, err := parseAddr(m.Data)
if err != nil {
if cberr != nil {
cberr(fmt.Errorf("could not parse address: %v", err))
@ -400,7 +400,7 @@ func addrSubscribeAt(newNs, curNs netns.NsHandle, ch chan<- AddrUpdate, done <-c
}
ch <- AddrUpdate{LinkAddress: *addr.IPNet,
LinkIndex: ifindex,
LinkIndex: addr.LinkIndex,
NewAddr: msgType == unix.RTM_NEWADDR,
Flags: addr.Flags,
Scope: addr.Scope,

View File

@ -94,6 +94,10 @@ func DoTestAddr(t *testing.T, FunctionUndertest func(Link, *Addr) error) {
t.Fatalf("Address scope not set properly, got=%d, expected=%d", addrs[0].Scope, tt.expected.Scope)
}
if ifindex := link.Attrs().Index; ifindex != addrs[0].LinkIndex {
t.Fatalf("Address ifindex not set properly, got=%d, expected=%d", addrs[0].LinkIndex, ifindex)
}
if tt.expected.Peer != nil {
if !addrs[0].PeerEqual(*tt.expected) {
t.Fatalf("Peer Address ip no set properly, got=%s, expected=%s", addrs[0].Peer, tt.expected.Peer)