GithubHelp home page GithubHelp logo

jackpal / gateway Goto Github PK

View Code? Open in Web Editor NEW
225.0 5.0 69.0 114 KB

A golang library for discovering the address of a LAN gateway.

License: BSD 3-Clause "New" or "Revised" License

Go 94.98% Shell 5.02%

gateway's Introduction

gateway

A simple library for discovering the IP address of the default gateway.

Example:

package main

import (
    "fmt"

    "github.com/jackpal/gateway"
)

func main() {
    gateway, err := gateway.DiscoverGateway()
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Gateway:", gateway.String())
   }
}

Provides implementations for:

  • Darwin (macOS)
  • Dragonfly
  • FreeBSD
  • Linux
  • NetBSD
  • OpenBSD
  • Solaris and illumos
  • Windows

Other platforms use an implementation that always returns an error.

Pull requests for other OSs happily considered!

Versions

v1.0.15

Update dependencies to latest versions. This was done to squelch a github security alert caused by depending upon an old version of x/net. This is the first time I've updated module versions, the tests pass, so hopefully everything's good.

v1.0.14

v1.0.13

  • Add tools/check-cross-compile.sh to check that the code compiles for various OSs.
  • Fix compilation errors exposed by tools/check-cross-compile.sh.

v1.0.12

  • If there are multiple default gateways, Windows now returns the gateway with the lowest metric.
  • Fix solaris build break. (In theory, IDK how to test this easily.)
  • Upgrade to golang 1.21
  • Upgrade golang.org/x/net version, makes dependabot happy. Probably was not any actual security issue because gateway doesn't use any of the APIs of golang.org/x/net that had security issues.

v1.0.11

  • Implement DiscoverInterface for BSD-like OSes.

v1.0.10

  • Fix non-BSD-based builds.

v1.0.9

  • Add go.mod and go.sum files.
  • Use "golang.org/x/net/route" to implement all BSD variants.
    • As a side effect this adds support for Dragonfly and NetBSD.
  • Add example to README.
  • Remove broken continuous integration.

v1.0.8

  • Add support for OpenBSD
  • Linux parser now supports gateways with an IP address of 0.0.0.0
  • Fall back to netstat on darwin systems if route fails.
  • Simplify Linux /proc/net/route parsers.

gateway's People

Contributors

alejandrodnm avatar atakancolak avatar calmh avatar chmduquesne avatar dependabot[bot] avatar fireflycons avatar greatroar avatar jackpal avatar jech avatar joemiller avatar ndeloof avatar shrinidhi111 avatar tmm1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

gateway's Issues

Will not working on windows of non-Englisht language

In gateway_common.go:

func parseWindowsRoutePrint(output []byte) (net.IP, error) {
	lines := strings.Split(string(output), "\n")
	for idx, line := range lines {
		if strings.HasPrefix(line, "Active Routes:") {
			if len(lines) <= idx+2 {
				return nil, errNoGateway
			}
...

If default language is non-English, "Active Routes" will be translated.

don't hardcode paths for linux

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.

tests now hang in limited debian chroot

Hello!

I don't know if this is related to the newely merged commit, but the tests hang on my machine.

Here is the output:

    go test -v github.com/jackpal/gateway
=== RUN   TestGateway

//cc @calmh

better BSD detection without calling external commands

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())
    }
}

DiscoverInterface not in go package

Expected

What I got

  • DiscoverInterface not defined in gateway

How to fix

v1.0.9 build error on linux

branch: v1.0.9 (v1.0.8 has no error)
error:

go: downloading github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421
package client
	imports github.com/jackpal/gateway
	imports golang.org/x/net/route: build constraints exclude all Go files in /home/ubuntu/go/pkg/mod/golang.org/x/[email protected]/route

Windows implementation doesn't consider multiple default GW with different MTUs

Real example:

> route print 0.0.0.0
===========================================================================
Interface List
 19...00 05 9a 3c 7a 00 ......Cisco AnyConnect Secure Mobility Client Virtual Miniport Adapter for Windows x64
 37...00 15 5d 0e 76 41 ......Hyper-V Virtual Ethernet Adapter
 21...cc 15 31 1e 58 08 ......Microsoft Wi-Fi Direct Virtual Adapter
  9...ce 15 31 1e 58 07 ......Microsoft Wi-Fi Direct Virtual Adapter #2
  6...cc 15 31 1e 58 07 ......Intel(R) Wi-Fi 6 AX201 160MHz
 17...cc 15 31 1e 58 0b ......Bluetooth Device (Personal Area Network)
  1...........................Software Loopback Interface 1
===========================================================================

IPv4 Route Table
===========================================================================
Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0    192.168.100.1   192.168.100.74     50
          0.0.0.0          0.0.0.0       10.21.38.1      10.21.38.97      2
===========================================================================
Persistent Routes:
  None

IPv6 Route Table
===========================================================================
Active Routes:
  None
Persistent Routes:
  None

I think in this case some metric comparison needed

Please tag new release

I got the fork/exec /usr/bin/ip: no such file or directory error. But now I see this is already fixed. But using go get I get the very old 1.0.4 release :/

Panics on Windows when there is no default gateway

It tries to index into rows of output from "route print" that don't necessarily exist:

panic: runtime error: index out of range
goroutine 38788 [running]:
panic(0xb76840, 0xc082002020)
    c:/go/src/runtime/panic.go:481 +0x3f4
github.com/syncthing/syncthing/vendor/github.com/jackpal/gateway.DiscoverGateway(0x0, 0x0, 0x0, 0x0, 0x0)
    c:/jenkins/workspace/syncthing-release-windows/src/github.com/syncthing/syncthing/vendor/github.com/jackpal/gateway/gateway_windows.go:37 +0x4e6
github.com/syncthing/syncthing/lib/pmp.Discover(0x1a3185c5000, 0x2540be400, 0x0, 0x0, 0x0)
    c:/jenkins/workspace/syncthing-release-windows/src/github.com/syncthing/syncthing/lib/pmp/pmp.go:25 +0x48
github.com/syncthing/syncthing/lib/nat.discoverAll.func1(0x1a3185c5000, 0x2540be400, 0xc082218cc0, 0x30e3218, 0xc082e7a740, 0xdd8aa0)
    c:/jenkins/workspace/syncthing-release-windows/src/github.com/syncthing/syncthing/lib/nat/registry.go:32 +0x4c
created by github.com/syncthing/syncthing/lib/nat.discoverAll
    c:/jenkins/workspace/syncthing-release-windows/src/github.com/syncthing/syncthing/lib/nat/registry.go:36 +0x1bb

(syncthing/syncthing#3142)

please tag and version this project

Hello,

Can you please tag and version this project?

I am the Debian Maintainer for gateway and versioning would help Debian keep up with development.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.