douchensi8625
2017-03-21 14:46
浏览 108
已采纳

为了获得某些RTF_ *标志的值而使用的系统调用

Using go, I would like to obtain the value of some RTF_* flags, (UGHS) from netstat(1) man page:

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

Any idea of what syscall/methods could I use to retrieve does values? I see they are declared https://golang.org/pkg/syscall/ but would like to know to use them?

I need this to find the IP of gateways added to the route table, mainly when connecting to VPN's, currently using netstat for this (withing macOS, FreeBSD):

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

Any ideas?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtidai6519 2017-03-22 14:49
    已采纳

    Has @JimB suggested by using the route package I was available to query the current routes and get only does IP matching certain flags, om this case" UGSH, UGSc.

    Basic example code:

    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
    ", ip)
                    }
                }
            }
        }
    }
    
    点赞 打赏 评论
  • dqoqnmb163241 2017-03-21 15:49

    The equivalent of strace netstat (dtruss on MacOS, see https://opensourcehacker.com/2011/12/02/osx-strace-equivalent-dtruss-seeing-inside-applications-what-they-do-and-why-they-hang/) should give you a list of system calls it makes and you can decide what system calls you need to make for your problem.

    点赞 打赏 评论

相关推荐 更多相似问题