jackpal / gateway

A golang library for discovering the address of a LAN gateway.
BSD 3-Clause "New" or "Revised" License
227 stars 69 forks source link

better BSD detection without calling external commands #27

Closed MrDefacto closed 1 year ago

MrDefacto commented 3 years ago

My full example. Feel free to implement in your package.

package main

import (
    "net"
    "fmt"
    "errors"
    "syscall"
    "golang.org/x/net/route"
)

var (
    errNoGateway = errors.New("No gateway")
)

func GetGateway() (ip net.IP, err error) {
    rib, err := route.FetchRIB(syscall.AF_INET, syscall.NET_RT_DUMP, 0)
    if err != nil {
    return nil, err
    }

    msgs, err := route.ParseRIB(syscall.NET_RT_DUMP, rib)
    if err != nil {
    return nil, err
    }

    for _, m := range msgs {
    switch m := m.(type) {
    case *route.RouteMessage:
        var ip net.IP
        switch sa := m.Addrs[syscall.RTAX_GATEWAY].(type) {
        case *route.Inet4Addr:
            ip = net.IPv4(sa.IP[0], sa.IP[1], sa.IP[2], sa.IP[3])
            return ip, nil
        case *route.Inet6Addr:
            ip = make(net.IP, net.IPv6len)
            copy(ip, sa.IP[:])
            return ip, nil
        }
    }
    }
    return nil, errNoGateway
}

func main() {
    gateway, err := GetGateway()
    if err != nil {
    fmt.Println(err)
    } else {
    fmt.Println("Gateway:", gateway.String())
    }
}
jackpal commented 1 year ago

Thanks! Included in v1.0.9