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

为了获得某些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)
                    }
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?
  • ¥15 html5 qrcode 扫描器
  • ¥15 爬取网页信息并保存需要完整代码