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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度