jackpal / gateway

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

don't hardcode paths for linux #12

Closed mattetti closed 7 years ago

mattetti commented 8 years ago

ip and routes are in a different path on some of my machines and I modified the code to do the following in gateway_linux.go.

func binPath(execName string) string {
    cmd := exec.Command("which", execName)
    buf, _ := cmd.Output()
    return strings.Trim(string(buf), "\n")
}

func DiscoverGateway() (ip net.IP, err error) {
    ip, err = discoverGatewayUsingRoute()
    if err != nil {
        ip, err = discoverGatewayUsingIp()
    }
    return
}

func discoverGatewayUsingIp() (net.IP, error) {
    routeCmd := exec.Command(binPath("ip"), "route", "show")
    output, err := routeCmd.CombinedOutput()
    if err != nil {
        return nil, err
    }

    return parseLinuxIPRoute(output)
}

func discoverGatewayUsingRoute() (net.IP, error) {
    routeCmd := exec.Command(binPath("route"), "-n")
    output, err := routeCmd.CombinedOutput()
    if err != nil {
        return nil, err
    }

    return parseLinuxRoute(output)
}

You'd probably want to memoize the paths and check on errors but I think the direction is something this pkg should consider.

jackpal commented 8 years ago

The reason we use the Linux-standard hard-coded full paths is to avoid relying on $PATH, which could be missing or malformed or not include the route or ip commands.

Your suggestion roughly boils down to using PATH again, which is not what we want to do.

I would be willing to consider a patch that optionally used environment variables such as JACKPAL_GATEWAY_IP and JACKPAL_GATEWAY_ROUTE to let people override the default locations / program names.

yonderblue commented 8 years ago

:+1: for some kind of solution to the hard coding.

Perhaps a good solution would be use the path, and if not found then use the hard coded? Or vice versa?

mjgarton commented 7 years ago

I've hit this problem too.

How about trying a hard coded list of paths? There are unlikely to be more than about 4 possibilities.

If this sounds okay, I'd be happy to make the change and submit a PR.

mjgarton commented 7 years ago

https://github.com/jackpal/gateway/pull/14

jackpal commented 7 years ago

Gave up on hard coding the paths to ip and bin.