github.com/inazumav/sing-box@v0.0.0-20230926072359-ab51429a14f1/route/interface_finder.go (about)

     1  package route
     2  
     3  import (
     4  	"net"
     5  
     6  	"github.com/sagernet/sing/common/control"
     7  )
     8  
     9  var _ control.InterfaceFinder = (*myInterfaceFinder)(nil)
    10  
    11  type myInterfaceFinder struct {
    12  	interfaces []net.Interface
    13  }
    14  
    15  func (f *myInterfaceFinder) update() error {
    16  	ifs, err := net.Interfaces()
    17  	if err != nil {
    18  		return err
    19  	}
    20  	f.interfaces = ifs
    21  	return nil
    22  }
    23  
    24  func (f *myInterfaceFinder) updateInterfaces(interfaces []net.Interface) {
    25  	f.interfaces = interfaces
    26  }
    27  
    28  func (f *myInterfaceFinder) InterfaceIndexByName(name string) (interfaceIndex int, err error) {
    29  	for _, netInterface := range f.interfaces {
    30  		if netInterface.Name == name {
    31  			return netInterface.Index, nil
    32  		}
    33  	}
    34  	netInterface, err := net.InterfaceByName(name)
    35  	if err != nil {
    36  		return
    37  	}
    38  	f.update()
    39  	return netInterface.Index, nil
    40  }
    41  
    42  func (f *myInterfaceFinder) InterfaceNameByIndex(index int) (interfaceName string, err error) {
    43  	for _, netInterface := range f.interfaces {
    44  		if netInterface.Index == index {
    45  			return netInterface.Name, nil
    46  		}
    47  	}
    48  	netInterface, err := net.InterfaceByIndex(index)
    49  	if err != nil {
    50  		return
    51  	}
    52  	f.update()
    53  	return netInterface.Name, nil
    54  }