github.com/osrg/gobgp/v3@v3.30.0/pkg/config/oc/default_linux.go (about)

     1  // Copyright (C) 2016 Nippon Telegraph and Telephone Corporation.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    12  // implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  //go:build linux
    16  // +build linux
    17  
    18  package oc
    19  
    20  import (
    21  	"fmt"
    22  	"net"
    23  
    24  	"github.com/vishvananda/netlink"
    25  )
    26  
    27  func GetIPv6LinkLocalNeighborAddress(ifname string) (string, error) {
    28  	ifi, err := net.InterfaceByName(ifname)
    29  	if err != nil {
    30  		return "", err
    31  	}
    32  	neighs, err := netlink.NeighList(ifi.Index, netlink.FAMILY_V6)
    33  	if err != nil {
    34  		return "", err
    35  	}
    36  	cnt := 0
    37  	var addr net.IP
    38  	for _, neigh := range neighs {
    39  		local, err := isLocalLinkLocalAddress(ifi.Index, neigh.IP)
    40  		if err != nil {
    41  			return "", err
    42  		}
    43  		if neigh.State&netlink.NUD_FAILED == 0 && neigh.IP.IsLinkLocalUnicast() && !local {
    44  			addr = neigh.IP
    45  			cnt++
    46  		}
    47  	}
    48  
    49  	if cnt == 0 {
    50  		return "", fmt.Errorf("no ipv6 link-local neighbor found")
    51  	} else if cnt > 1 {
    52  		return "", fmt.Errorf("found %d link-local neighbors. only support p2p link", cnt)
    53  	}
    54  
    55  	return fmt.Sprintf("%s%%%s", addr, ifname), nil
    56  }
    57  
    58  func isLocalLinkLocalAddress(ifindex int, addr net.IP) (bool, error) {
    59  	ifi, err := net.InterfaceByIndex(ifindex)
    60  	if err != nil {
    61  		return false, err
    62  	}
    63  	addrs, err := ifi.Addrs()
    64  	if err != nil {
    65  		return false, err
    66  	}
    67  	for _, a := range addrs {
    68  		if ip, _, _ := net.ParseCIDR(a.String()); addr.Equal(ip) {
    69  			return true, nil
    70  		}
    71  	}
    72  	return false, nil
    73  }