sing-box/route/interface_finder.go

55 lines
1.1 KiB
Go
Raw Normal View History

2022-09-14 12:46:02 +08:00
package route
import (
"net"
"github.com/sagernet/sing/common/control"
)
var _ control.InterfaceFinder = (*myInterfaceFinder)(nil)
type myInterfaceFinder struct {
2023-04-18 14:04:09 +08:00
interfaces []net.Interface
2022-09-14 12:46:02 +08:00
}
func (f *myInterfaceFinder) update() error {
ifs, err := net.Interfaces()
if err != nil {
return err
}
2023-04-18 14:04:09 +08:00
f.interfaces = ifs
2022-09-14 12:46:02 +08:00
return nil
}
2023-04-18 14:04:09 +08:00
func (f *myInterfaceFinder) updateInterfaces(interfaces []net.Interface) {
f.interfaces = interfaces
}
2022-09-14 12:46:02 +08:00
func (f *myInterfaceFinder) InterfaceIndexByName(name string) (interfaceIndex int, err error) {
2023-04-18 14:04:09 +08:00
for _, netInterface := range f.interfaces {
2022-09-14 12:46:02 +08:00
if netInterface.Name == name {
return netInterface.Index, nil
}
}
netInterface, err := net.InterfaceByName(name)
if err != nil {
return
}
f.update()
return netInterface.Index, nil
}
func (f *myInterfaceFinder) InterfaceNameByIndex(index int) (interfaceName string, err error) {
2023-04-18 14:04:09 +08:00
for _, netInterface := range f.interfaces {
2022-09-14 12:46:02 +08:00
if netInterface.Index == index {
return netInterface.Name, nil
}
}
netInterface, err := net.InterfaceByIndex(index)
if err != nil {
return
}
f.update()
return netInterface.Name, nil
}