clash/test/util_darwin_test.go

72 lines
1.4 KiB
Go
Raw Normal View History

2021-05-17 12:33:00 +00:00
package main
import (
"fmt"
"net"
2022-06-09 10:00:41 +00:00
"net/netip"
2021-05-17 12:33:00 +00:00
"syscall"
"golang.org/x/net/route"
)
2022-06-09 10:00:41 +00:00
func defaultRouteIP() (netip.Addr, error) {
2021-05-17 12:33:00 +00:00
idx, err := defaultRouteInterfaceIndex()
if err != nil {
2022-06-09 10:00:41 +00:00
return netip.Addr{}, err
2021-05-17 12:33:00 +00:00
}
iface, err := net.InterfaceByIndex(idx)
if err != nil {
2022-06-09 10:00:41 +00:00
return netip.Addr{}, err
2021-05-17 12:33:00 +00:00
}
addrs, err := iface.Addrs()
if err != nil {
2022-06-09 10:00:41 +00:00
return netip.Addr{}, err
2021-05-17 12:33:00 +00:00
}
for _, addr := range addrs {
ip := addr.(*net.IPNet).IP
if ip.To4() != nil {
2022-06-09 10:00:41 +00:00
a, _ := netip.AddrFromSlice(ip)
return a, nil
2021-05-17 12:33:00 +00:00
}
}
2022-06-09 10:00:41 +00:00
return netip.Addr{}, err
2021-05-17 12:33:00 +00:00
}
func defaultRouteInterfaceIndex() (int, error) {
rib, err := route.FetchRIB(syscall.AF_UNSPEC, syscall.NET_RT_DUMP2, 0)
if err != nil {
return 0, fmt.Errorf("route.FetchRIB: %w", err)
}
msgs, err := route.ParseRIB(syscall.NET_RT_IFLIST2, rib)
if err != nil {
return 0, fmt.Errorf("route.ParseRIB: %w", err)
}
for _, message := range msgs {
routeMessage := message.(*route.RouteMessage)
if routeMessage.Flags&(syscall.RTF_UP|syscall.RTF_GATEWAY|syscall.RTF_STATIC) == 0 {
continue
}
addresses := routeMessage.Addrs
destination, ok := addresses[0].(*route.Inet4Addr)
if !ok {
continue
}
if destination.IP != [4]byte{0, 0, 0, 0} {
continue
}
switch addresses[1].(type) {
case *route.Inet4Addr:
return routeMessage.Index, nil
default:
continue
}
}
return 0, fmt.Errorf("ambiguous gateway interfaces found")
}