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

时间:2017-03-21 14:46:17

标签: go network-programming system-calls

使用go,我想从netstat(1)手册页获取一些RTF_*标志的值,(UGHS):

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

我可以使用什么系统调用/方法来检索值?我看到他们被宣布为https://golang.org/pkg/syscall/但是想知道使用它们吗?

我需要这样才能找到添加到路由表中的网关IP,主要是在连接到VPN时,目前正在使用netstat(使用macOS,FreeBSD):

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

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

@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)
                }
            }
        }
    }
}

答案 1 :(得分:0)

相当于strace netstat(在MacOS上展示,请参阅https://opensourcehacker.com/2011/12/02/osx-strace-equivalent-dtruss-seeing-inside-applications-what-they-do-and-why-they-hang/)应该会为您提供系统调用列表,您可以决定需要为您的问题调用哪些系统调用。