Skip to content

Instantly share code, notes, and snippets.

@jftuga
Forked from abimaelmartell/default_gateway.go
Created August 12, 2021 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jftuga/3649d5e4a6b8c922005d53230adfa240 to your computer and use it in GitHub Desktop.
Save jftuga/3649d5e4a6b8c922005d53230adfa240 to your computer and use it in GitHub Desktop.
Get default gateway by parsing RIB information using the net/route package. BSD Only.
package main
import (
"fmt"
"golang.org/x/net/route"
)
var defaultRoute = [4]byte{0, 0, 0, 0}
func main() {
rib, _ := route.FetchRIB(0, route.RIBTypeRoute, 0)
messages, err := route.ParseRIB(route.RIBTypeRoute, rib)
if err != nil {
return
}
for _, message := range messages {
route_message := message.(*route.RouteMessage)
addresses := route_message.Addrs
var destination, gateway *route.Inet4Addr
ok := false
if destination, ok = addresses[0].(*route.Inet4Addr); !ok {
continue
}
if gateway, ok = addresses[1].(*route.Inet4Addr); !ok {
continue
}
if destination == nil || gateway == nil {
continue
}
if destination.IP == defaultRoute {
fmt.Println(gateway.IP)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment