Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better BSD detection without calling external commands #27

Closed
MrDefacto opened this issue Feb 22, 2021 · 1 comment
Closed

better BSD detection without calling external commands #27

MrDefacto opened this issue Feb 22, 2021 · 1 comment

Comments

@MrDefacto
Copy link

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
Copy link
Owner

jackpal commented Mar 31, 2023

Thanks! Included in v1.0.9

@jackpal jackpal closed this as completed Mar 31, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants