github.com/osrg/gobgp@v2.0.0+incompatible/internal/pkg/config/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  // +build linux
    16  
    17  package config
    18  
    19  import (
    20  	"fmt"
    21  	"net"
    22  
    23  	"github.com/vishvananda/netlink"
    24  )
    25  
    26  func GetIPv6LinkLocalNeighborAddress(ifname string) (string, error) {
    27  	ifi, err := net.InterfaceByName(ifname)
    28  	if err != nil {
    29  		return "", err
    30  	}
    31  	neighs, err := netlink.NeighList(ifi.Index, netlink.FAMILY_V6)
    32  	if err != nil {
    33  		return "", err
    34  	}
    35  	cnt := 0
    36  	var addr net.IP
    37  	for _, neigh := range neighs {
    38  		local, err := isLocalLinkLocalAddress(ifi.Index, neigh.IP)
    39  		if err != nil {
    40  			return "", err
    41  		}
    42  		if neigh.State&netlink.NUD_FAILED == 0 && neigh.IP.IsLinkLocalUnicast() && !local {
    43  			addr = neigh.IP
    44  			cnt++
    45  		}
    46  	}
    47  
    48  	if cnt == 0 {
    49  		return "", fmt.Errorf("no ipv6 link-local neighbor found")
    50  	} else if cnt > 1 {
    51  		return "", fmt.Errorf("found %d link-local neighbors. only support p2p link", cnt)
    52  	}
    53  
    54  	return fmt.Sprintf("%s%%%s", addr, ifname), nil
    55  }
    56  
    57  func isLocalLinkLocalAddress(ifindex int, addr net.IP) (bool, error) {
    58  	ifi, err := net.InterfaceByIndex(ifindex)
    59  	if err != nil {
    60  		return false, err
    61  	}
    62  	addrs, err := ifi.Addrs()
    63  	if err != nil {
    64  		return false, err
    65  	}
    66  	for _, a := range addrs {
    67  		if ip, _, _ := net.ParseCIDR(a.String()); addr.Equal(ip) {
    68  			return true, nil
    69  		}
    70  	}
    71  	return false, nil
    72  }