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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?