nbari
nbari

Reputation: 26925

what syscall to use in order to obtain the value of some RTF_* flags

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?

Upvotes: 3

Views: 450

Answers (2)

nbari
nbari

Reputation: 26925

As @JimB suggested by using the route package I was able to query the current routes and get only IP's matching certain flags, in 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\n", ip)
                }
            }
        }
    }
}

Upvotes: 3

Ravi R
Ravi R

Reputation: 1782

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.

Upvotes: 0

Related Questions