| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | ) |
| 12 | |
| 13 | func linuxPhysicalInterface(ctx context.Context) (string, error) { |
| 14 | if err := ctx.Err(); err != nil { |
| 15 | return "", err |
| 16 | } |
| 17 | routes, err := os.ReadFile("/proc/net/route") |
| 18 | if err != nil { |
| 19 | return "", errors.New("无法读取 Linux IPv4 路由,请检查主机网络后重试") |
| 20 | } |
| 21 | interfaces, err := net.Interfaces() |
| 22 | if err != nil { |
| 23 | return "", err |
| 24 | } |
| 25 | usable := map[string]bool{} |
| 26 | for _, iface := range interfaces { |
| 27 | if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 { |
| 28 | continue |
| 29 | } |
| 30 | |
| 31 | |
| 32 | if _, err := os.Stat(filepath.Join("/sys/class/net", iface.Name, "device")); err != nil { |
| 33 | continue |
| 34 | } |
| 35 | addresses, _ := iface.Addrs() |
| 36 | for _, address := range addresses { |
| 37 | ip, _, err := net.ParseCIDR(address.String()) |
| 38 | if err == nil && ip.To4() != nil && !ip.IsLinkLocalUnicast() && !ip.IsUnspecified() { |
| 39 | usable[iface.Name] = true |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | return selectLinuxPhysicalInterface(string(routes), usable) |
| 44 | } |
| 45 | |
| 46 | func selectLinuxPhysicalInterface(routes string, usable map[string]bool) (string, error) { |
| 47 | selected := "" |
| 48 | var best uint64 |
| 49 | for _, line := range strings.Split(routes, "\n") { |
| 50 | fields := strings.Fields(line) |
| 51 | if len(fields) < 8 || !usable[fields[0]] || fields[1] != "00000000" || fields[7] != "00000000" { |
| 52 | continue |
| 53 | } |
| 54 | flags, flagErr := strconv.ParseUint(fields[3], 16, 32) |
| 55 | metric, metricErr := strconv.ParseUint(fields[6], 10, 64) |
| 56 | |
| 57 | if flagErr != nil || metricErr != nil || flags&1 == 0 || flags&0x200 != 0 { |
| 58 | continue |
| 59 | } |
| 60 | if selected == "" || metric < best || metric == best && fields[0] < selected { |
| 61 | selected, best = fields[0], metric |
| 62 | } |
| 63 | } |
| 64 | if selected == "" { |
| 65 | return "", errors.New("未找到带 IPv4 默认路由的物理或云主机网卡;Cage 外网保持关闭,请连接网络后重试") |
| 66 | } |
| 67 | return selected, nil |
| 68 | } |