使用什么系统调用来获取某些 RTF_* 标志的值

what syscall to use in order to obtain the value of some RTF_* flags

使用 go, I would like to obtain the value of some RTF_* flags, (UGHS) from netstat(1) 手册页:

G     RTF_GATEWAY  Destination requires forwarding by intermediary
H     RTF_HOST     Host entry (net otherwise)
S     RTF_STATIC   Manually added
U     RTF_UP       Route usable

知道我可以使用什么 syscall/methods 来检索值吗?我看到它们被声明为 https://golang.org/pkg/syscall/ 但想知道如何使用它们?

我需要这个来找到添加到路由 table 的网关的 IP,主要是在连接到 VPN 时,目前为此使用 netstat(使用 macOS、FreeBSD):

 netstat -rna -f inet | grep UGHS | awk '{print }' 

有什么想法吗?

strace netstat 的等价物(MacOS 上的 dtruss,参见 https://opensourcehacker.com/2011/12/02/osx-strace-equivalent-dtruss-seeing-inside-applications-what-they-do-and-why-they-hang/)应该给你一个系统调用的列表,你可以决定你需要为你的问题进行哪些系统调用。

正如@JimB 建议的那样,通过使用 route 包,我能够查询当前路由并仅获取与某些标志匹配的 IP,在本例中为“UGSHUGSc

基本示例代码:

package main

import (
    "fmt"
    "net"
    "syscall"

    "golang.org/x/net/route"
)

const (
    UGSH = syscall.RTF_UP | syscall.RTF_GATEWAY | syscall.RTF_STATIC | syscall.RTF_HOST
    UGSc = syscall.RTF_UP | syscall.RTF_GATEWAY | syscall.RTF_STATIC | syscall.RTF_PRCLONING
)

func main() {
    if rib, err := route.FetchRIB(syscall.AF_UNSPEC, route.RIBTypeRoute, 0); err == nil {
        if msgs, err := route.ParseRIB(route.RIBTypeRoute, rib); err == nil {
            for _, msg := range msgs {
                m := msg.(*route.RouteMessage)
                if m.Flags == UGSH || m.Flags == UGSc {
                    var ip net.IP
                    switch a := m.Addrs[syscall.AF_UNSPEC].(type) {
                    case *route.Inet4Addr:
                        ip = net.IPv4(a.IP[0], a.IP[1], a.IP[2], a.IP[3])
                    case *route.Inet6Addr:
                        ip = make(net.IP, net.IPv6len)
                        copy(ip, a.IP[:])
                    }
                    fmt.Printf("ip = %s\n", ip)
                }
            }
        }
    }
}