├── version.json ├── .github └── workflows │ ├── stale.yml │ ├── generated-pr.yml │ ├── tagpush.yml │ ├── releaser.yml │ ├── go-check.yml │ ├── release-check.yml │ └── go-test.yml ├── go.mod ├── netroute_stub.go ├── go.sum ├── LICENSE ├── router.go ├── netroute_test.go ├── README.md ├── sockaddr_windows.go ├── netroute_plan9.go ├── common.go ├── netroute_bsd_test.go ├── netroute_windows.go ├── netroute_linux.go └── netroute_bsd.go /version.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "v0.4.0" 3 | } 4 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Close Stale Issues 2 | 3 | on: 4 | schedule: 5 | - cron: '0 0 * * *' 6 | workflow_dispatch: 7 | 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | 12 | jobs: 13 | stale: 14 | uses: ipdxco/unified-github-workflows/.github/workflows/reusable-stale-issue.yml@v1 15 | -------------------------------------------------------------------------------- /.github/workflows/generated-pr.yml: -------------------------------------------------------------------------------- 1 | name: Close Generated PRs 2 | 3 | on: 4 | schedule: 5 | - cron: '0 0 * * *' 6 | workflow_dispatch: 7 | 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | 12 | jobs: 13 | stale: 14 | uses: ipdxco/unified-github-workflows/.github/workflows/reusable-generated-pr.yml@v1 15 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/libp2p/go-netroute 2 | 3 | go 1.24 4 | 5 | require ( 6 | github.com/stretchr/testify v1.10.0 7 | golang.org/x/net v0.37.0 8 | golang.org/x/sys v0.31.0 9 | ) 10 | 11 | require ( 12 | github.com/davecgh/go-spew v1.1.1 // indirect 13 | github.com/pmezard/go-difflib v1.0.0 // indirect 14 | gopkg.in/yaml.v3 v3.0.1 // indirect 15 | ) 16 | -------------------------------------------------------------------------------- /.github/workflows/tagpush.yml: -------------------------------------------------------------------------------- 1 | name: Tag Push Checker 2 | 3 | on: 4 | push: 5 | tags: 6 | - v* 7 | 8 | permissions: 9 | contents: read 10 | issues: write 11 | 12 | concurrency: 13 | group: ${{ github.workflow }}-${{ github.ref }} 14 | cancel-in-progress: true 15 | 16 | jobs: 17 | releaser: 18 | uses: ipdxco/unified-github-workflows/.github/workflows/tagpush.yml@v1.0 19 | -------------------------------------------------------------------------------- /.github/workflows/releaser.yml: -------------------------------------------------------------------------------- 1 | name: Releaser 2 | 3 | on: 4 | push: 5 | paths: [ 'version.json' ] 6 | workflow_dispatch: 7 | 8 | permissions: 9 | contents: write 10 | 11 | concurrency: 12 | group: ${{ github.workflow }}-${{ github.sha }} 13 | cancel-in-progress: true 14 | 15 | jobs: 16 | releaser: 17 | uses: ipdxco/unified-github-workflows/.github/workflows/releaser.yml@v1.0 18 | -------------------------------------------------------------------------------- /.github/workflows/go-check.yml: -------------------------------------------------------------------------------- 1 | name: Go Checks 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: ["master"] 7 | workflow_dispatch: 8 | 9 | permissions: 10 | contents: read 11 | 12 | concurrency: 13 | group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event_name == 'push' && github.sha || github.ref }} 14 | cancel-in-progress: true 15 | 16 | jobs: 17 | go-check: 18 | uses: ipdxco/unified-github-workflows/.github/workflows/go-check.yml@v1.0 19 | -------------------------------------------------------------------------------- /netroute_stub.go: -------------------------------------------------------------------------------- 1 | // A stub routing table conformant interface for js/wasm environments. 2 | 3 | //go:build (js && wasm) || (wasip1 && wasm) 4 | 5 | package netroute 6 | 7 | import ( 8 | "net" 9 | ) 10 | 11 | func New() (Router, error) { 12 | rtr := &router{} 13 | rtr.ifaces = make(map[int]net.Interface) 14 | rtr.ifaces[0] = net.Interface{} 15 | rtr.addrs = make(map[int]ipAddrs) 16 | rtr.addrs[0] = ipAddrs{} 17 | rtr.v4 = []*rtInfo{{}} 18 | rtr.v6 = []*rtInfo{{}} 19 | return rtr, nil 20 | } 21 | -------------------------------------------------------------------------------- /.github/workflows/release-check.yml: -------------------------------------------------------------------------------- 1 | name: Release Checker 2 | 3 | on: 4 | pull_request_target: 5 | paths: [ 'version.json' ] 6 | types: [ opened, synchronize, reopened, labeled, unlabeled ] 7 | workflow_dispatch: 8 | 9 | permissions: 10 | contents: write 11 | pull-requests: write 12 | 13 | concurrency: 14 | group: ${{ github.workflow }}-${{ github.ref }} 15 | cancel-in-progress: true 16 | 17 | jobs: 18 | release-check: 19 | uses: ipdxco/unified-github-workflows/.github/workflows/release-check.yml@v1.0 20 | -------------------------------------------------------------------------------- /.github/workflows/go-test.yml: -------------------------------------------------------------------------------- 1 | name: Go Test 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: ["master"] 7 | workflow_dispatch: 8 | 9 | permissions: 10 | contents: read 11 | 12 | concurrency: 13 | group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event_name == 'push' && github.sha || github.ref }} 14 | cancel-in-progress: true 15 | 16 | jobs: 17 | go-test: 18 | uses: ipdxco/unified-github-workflows/.github/workflows/go-test.yml@v1.0 19 | secrets: 20 | CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} 21 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 6 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 7 | golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= 8 | golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= 9 | golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= 10 | golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 11 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 12 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 13 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 14 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 15 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 Will Scott. All rights reserved. 2 | Copyright (c) 2012 Google, Inc. All rights reserved. 3 | Copyright (c) 2009-2011 Andreas Krennmair. All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | * Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above 12 | copyright notice, this list of conditions and the following disclaimer 13 | in the documentation and/or other materials provided with the 14 | distribution. 15 | * Neither the name of Andreas Krennmair, Google, nor the names of its 16 | contributors may be used to endorse or promote products derived from 17 | this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 20 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 21 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 22 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 23 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 24 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 25 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /router.go: -------------------------------------------------------------------------------- 1 | package netroute 2 | 3 | import "net" 4 | 5 | // Router implements simple IPv4/IPv6 routing based on the kernel's routing 6 | // table. This routing library has very few features and may actually route 7 | // incorrectly in some cases, but it should work the majority of the time. 8 | // 9 | // This interface was copied from https://github.com/google/gopacket 10 | // 11 | // Copyright 2012 Google, Inc. All rights reserved. 12 | // 13 | // Use of this source code is governed by a BSD-style license 14 | // that can be found in the LICENSE file in the root of the source 15 | // tree. 16 | type Router interface { 17 | // Route returns where to route a packet based on the packet's source 18 | // and destination IP address. 19 | // 20 | // Callers may pass in nil for src, in which case the src is treated as 21 | // either 0.0.0.0 or ::, depending on whether dst is a v4 or v6 address. 22 | // 23 | // It returns the interface on which to send the packet, the gateway IP 24 | // to send the packet to (if necessary), the preferred src IP to use (if 25 | // available). If the preferred src address is not given in the routing 26 | // table, the first IP address of the interface is provided. 27 | // 28 | // If an error is encountered, iface, geteway, and 29 | // preferredSrc will be nil, and err will be set. 30 | Route(dst net.IP) (iface *net.Interface, gateway, preferredSrc net.IP, err error) 31 | 32 | // RouteWithSrc routes based on source information as well as destination 33 | // information. Either or both of input/src can be nil. If both are, this 34 | // should behave exactly like Route(dst) 35 | RouteWithSrc(input net.HardwareAddr, src, dst net.IP) (iface *net.Interface, gateway, preferredSrc net.IP, err error) 36 | } 37 | -------------------------------------------------------------------------------- /netroute_test.go: -------------------------------------------------------------------------------- 1 | package netroute 2 | 3 | import ( 4 | "net" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | func TestRoute(t *testing.T) { 10 | r, err := New() 11 | if err != nil { 12 | t.Fatal(err) 13 | } 14 | 15 | ifs, err := net.Interfaces() 16 | if err != nil || len(ifs) == 0 { 17 | t.Skip("Can't test routing without access to system interfaces") 18 | } 19 | 20 | var localAddr net.IP 21 | var hasV6 bool 22 | addrs, err := ifs[0].Addrs() 23 | if err != nil { 24 | t.Fatal(err) 25 | } 26 | for _, addr := range addrs { 27 | if strings.HasPrefix(addr.Network(), "ip") { 28 | localAddr, _, _ = net.ParseCIDR(addr.String()) 29 | break 30 | } 31 | } 32 | for _, addr := range addrs { 33 | if strings.HasPrefix(addr.Network(), "ip") { 34 | _, ipn, _ := net.ParseCIDR(addr.String()) 35 | if ipn.IP.To4() == nil && 36 | !ipn.IP.IsLoopback() && 37 | !ipn.IP.IsInterfaceLocalMulticast() && 38 | !ipn.IP.IsLinkLocalUnicast() && 39 | !ipn.IP.IsLinkLocalMulticast() { 40 | hasV6 = true 41 | break 42 | } 43 | } 44 | } 45 | 46 | _, gw, src, err := r.Route(localAddr) 47 | if err != nil { 48 | t.Fatal(err) 49 | } 50 | // FreeBSD returns lo as IFP of route 51 | // root@bsd1:~/src/me/go-netroute # route -nv get 192.168.64.7 52 | // route to: 192.168.64.7 53 | // destination: 192.168.64.7 54 | // fib: 0 55 | // interface: lo0 56 | if gw != nil || (!src.Equal(localAddr) && !src.Equal(net.IP([]byte{127, 0, 0, 1}))) { 57 | t.Fatalf("Did not expect gateway for %v->%v: %v", src, localAddr, gw) 58 | } 59 | 60 | // Route to somewhere external should. 61 | _, gw, _, err = r.Route(net.IPv4(8, 8, 8, 8)) 62 | if err != nil { 63 | t.Fatal(err) 64 | } 65 | if gw == nil { 66 | t.Fatalf("Did not expect direct link to 8.8.8.8. Are you Google?") 67 | } 68 | 69 | // Route to v4 and v6 should differ. 70 | if !hasV6 { 71 | return 72 | } 73 | _, v6gw, _, err := r.Route(net.ParseIP("2607:f8b0:400a:809::200e")) // at one point google. 74 | if err != nil { 75 | t.Fatal(err) 76 | } 77 | if v6gw.Equal(gw) { 78 | t.Fatalf("did not expect a v4 gw for a v6 route.") 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Go Netroute 2 | === 3 | 4 | [![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://protocol.ai) 5 | [![](https://img.shields.io/badge/project-libp2p-yellow.svg?style=flat-square)](http://github.com/libp2p/libp2p) 6 | [![Build Status](https://travis-ci.com/libp2p/go-netroute.svg?branch=master)](https://travis-ci.com/libp2p/go-netroute) 7 | 8 | A cross-platform implementation of the [`gopacket/routing.Router`](https://godoc.org/github.com/google/gopacket/routing#Router) interface. 9 | 10 | This library is derived from `gopacket` for linux, `x/net/route` for mac, and `iphlpapi.dll` for windows. 11 | 12 | ## Table of Contents 13 | 14 | - [Install](#install) 15 | - [Usage](#usage) 16 | - [Documentation](#documentation) 17 | - [Contribute](#contribute) 18 | - [License](#license) 19 | 20 | ## Install 21 | 22 | ``` 23 | go get github.com/libp2p/go-netroute 24 | ``` 25 | 26 | ## Usage 27 | 28 | To be used for querying the local OS routing table. 29 | 30 | ```go 31 | import ( 32 | netroute "github.com/libp2p/go-netroute" 33 | ) 34 | 35 | func main() { 36 | r, err := netroute.New() 37 | if err != nil { 38 | panic(err) 39 | } 40 | iface, gw, src, err := r.Route(net.IPv4(127, 0, 0, 1)) 41 | fmt.Printf("%v, %v, %v, %v\n", iface, gw, src, err) 42 | } 43 | ``` 44 | 45 | ## Documentation 46 | 47 | See the [gopacket](https://github.com/google/gopacket/blob/master/routing/) interface for thoughts on design, 48 | and [godoc](https://godoc.org/github.com/libp2p/go-netroute) for API documentation. 49 | 50 | ## Contribute 51 | 52 | Contributions welcome. Please check out [the issues](https://github.com/libp2p/go-netroute/issues). 53 | 54 | Check out our [contributing document](https://github.com/libp2p/community/blob/master/contributing.md) for more information on how we work, and about contributing in general. Please be aware that all interactions related to multiformats are subject to the IPFS [Code of Conduct](https://github.com/ipfs/community/blob/master/code-of-conduct.md). 55 | 56 | Small note: If editing the README, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification. 57 | 58 | ## License 59 | 60 | [BSD](LICENSE) © Will Scott, and the Gopacket authors (i.e. Google) 61 | -------------------------------------------------------------------------------- /sockaddr_windows.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | 3 | package netroute 4 | 5 | import ( 6 | "net" 7 | "strconv" 8 | "syscall" 9 | "unsafe" 10 | 11 | "golang.org/x/sys/windows" 12 | ) 13 | 14 | // socklen is a type for the length of a sockaddr. 15 | type socklen uint 16 | 17 | // ipAndZoneToSockaddr converts a net.IP (with optional IPv6 Zone) to a Sockaddr 18 | // Returns nil if conversion fails. 19 | func ipAndZoneToSockaddr(ip net.IP, zone string) windows.Sockaddr { 20 | // Unspecified? 21 | if ip == nil { 22 | if zone != "" { 23 | return &windows.SockaddrInet6{ZoneId: uint32(ip6ZoneToInt(zone))} 24 | } 25 | return new(windows.SockaddrInet4) 26 | } 27 | 28 | // Valid IPv4? 29 | if ip4 := ip.To4(); ip4 != nil && zone == "" { 30 | var buf [4]byte 31 | copy(buf[:], ip4) // last 4 bytes 32 | return &windows.SockaddrInet4{Addr: buf} 33 | } 34 | 35 | // Valid IPv6 address? 36 | if ip6 := ip.To16(); ip6 != nil { 37 | var buf [16]byte 38 | copy(buf[:], ip6) 39 | return &windows.SockaddrInet6{Addr: buf, ZoneId: uint32(ip6ZoneToInt(zone))} 40 | } 41 | 42 | return nil 43 | } 44 | 45 | // sockaddrToIPAndZone converts a Sockaddr to a net.IP (with optional IPv6 Zone) 46 | // Returns nil if conversion fails. 47 | func sockaddrToIPAndZone(sa windows.Sockaddr) (net.IP, string) { 48 | switch sa := sa.(type) { 49 | case *windows.SockaddrInet4: 50 | ip := make([]byte, 16) 51 | // V4InV6Prefix 52 | ip[10] = 0xff 53 | ip[11] = 0xff 54 | copy(ip[12:16], sa.Addr[:]) 55 | return ip, "" 56 | case *windows.SockaddrInet6: 57 | ip := make([]byte, 16) 58 | copy(ip, sa.Addr[:]) 59 | return ip, ip6ZoneToString(int(sa.ZoneId)) 60 | } 61 | return nil, "" 62 | } 63 | 64 | func sockaddrToAny(sa windows.Sockaddr) (*windows.RawSockaddrAny, socklen, error) { 65 | if sa == nil { 66 | return nil, 0, syscall.EINVAL 67 | } 68 | 69 | switch sa := sa.(type) { 70 | case *windows.SockaddrInet4: 71 | if sa.Port < 0 || sa.Port > 0xFFFF { 72 | return nil, 0, syscall.EINVAL 73 | } 74 | raw := new(windows.RawSockaddrAny) 75 | raw.Addr.Family = windows.AF_INET 76 | raw4 := (*windows.RawSockaddrInet4)(unsafe.Pointer(raw)) 77 | p := (*[2]byte)(unsafe.Pointer(&raw4.Port)) 78 | p[0] = byte(sa.Port >> 8) 79 | p[1] = byte(sa.Port) 80 | for i := 0; i < len(sa.Addr); i++ { 81 | raw4.Addr[i] = sa.Addr[i] 82 | } 83 | return raw, socklen(unsafe.Sizeof(*raw4)), nil 84 | case *windows.SockaddrInet6: 85 | if sa.Port < 0 || sa.Port > 0xFFFF { 86 | return nil, 0, syscall.EINVAL 87 | } 88 | raw := new(windows.RawSockaddrAny) 89 | raw.Addr.Family = windows.AF_INET6 90 | raw6 := (*windows.RawSockaddrInet6)(unsafe.Pointer(raw)) 91 | p := (*[2]byte)(unsafe.Pointer(&raw6.Port)) 92 | p[0] = byte(sa.Port >> 8) 93 | p[1] = byte(sa.Port) 94 | raw6.Scope_id = sa.ZoneId 95 | for i := 0; i < len(sa.Addr); i++ { 96 | raw6.Addr[i] = sa.Addr[i] 97 | } 98 | return raw, socklen(unsafe.Sizeof(*raw6)), nil 99 | case *windows.SockaddrUnix: 100 | return nil, 0, syscall.EWINDOWS 101 | } 102 | return nil, 0, syscall.EAFNOSUPPORT 103 | } 104 | 105 | // from: go/src/pkg/net/ipsock.go 106 | 107 | // ip6ZoneToString converts an IP6 Zone unix int to a net string 108 | // returns "" if zone is 0 109 | func ip6ZoneToString(zone int) string { 110 | if zone == 0 { 111 | return "" 112 | } 113 | if ifi, err := net.InterfaceByIndex(zone); err == nil { 114 | return ifi.Name 115 | } 116 | return strconv.Itoa(zone) 117 | } 118 | 119 | // ip6ZoneToInt converts an IP6 Zone net string to a unix int 120 | // returns 0 if zone is "" 121 | func ip6ZoneToInt(zone string) int { 122 | if zone == "" { 123 | return 0 124 | } 125 | if ifi, err := net.InterfaceByName(zone); err == nil { 126 | return ifi.Index 127 | } 128 | n, _ := strconv.ParseInt(zone, 10, 32) 129 | return int(n) 130 | } 131 | -------------------------------------------------------------------------------- /netroute_plan9.go: -------------------------------------------------------------------------------- 1 | // Generate a local routing table structure following the code at 2 | // https://github.com/google/gopacket/blob/master/routing/routing.go 3 | // 4 | // Plan 9 networking is described here: http://9p.io/magic/man2html/3/ip 5 | 6 | package netroute 7 | 8 | import ( 9 | "bytes" 10 | "fmt" 11 | "net" 12 | "os" 13 | "strconv" 14 | "strings" 15 | ) 16 | 17 | const netdir = "/net" 18 | 19 | func New() (Router, error) { 20 | rtr := &router{} 21 | rtr.ifaces = make(map[int]net.Interface) 22 | rtr.addrs = make(map[int]ipAddrs) 23 | ifaces, err := net.Interfaces() 24 | if err != nil { 25 | return nil, fmt.Errorf("could not get interfaces: %v", err) 26 | } 27 | for _, iface := range ifaces { 28 | rtr.ifaces[iface.Index] = iface 29 | var addrs ipAddrs 30 | ifaceAddrs, err := iface.Addrs() 31 | if err != nil { 32 | return nil, err 33 | } 34 | for _, addr := range ifaceAddrs { 35 | if inet, ok := addr.(*net.IPNet); ok { 36 | // Go has a nasty habit of giving you IPv4s as ::ffff:1.2.3.4 instead of 1.2.3.4. 37 | // We want to use mapped v4 addresses as v4 preferred addresses, never as v6 38 | // preferred addresses. 39 | if v4 := inet.IP.To4(); v4 != nil { 40 | if addrs.v4 == nil { 41 | addrs.v4 = v4 42 | } 43 | } else if addrs.v6 == nil { 44 | addrs.v6 = inet.IP 45 | } 46 | } 47 | } 48 | rtr.addrs[iface.Index] = addrs 49 | } 50 | 51 | rtr.v4, rtr.v6, err = parseIPRoutes() 52 | if err != nil { 53 | return nil, err 54 | } 55 | return rtr, nil 56 | } 57 | 58 | func parseIPRoutes() (v4, v6 []*rtInfo, err error) { 59 | buf, err := os.ReadFile(netdir + "/iproute") 60 | if err != nil { 61 | return nil, nil, err 62 | } 63 | 64 | for { 65 | i := bytes.IndexRune(buf, '\n') 66 | if i <= 0 { 67 | break 68 | } 69 | f := strings.Fields(string(buf[:i])) 70 | buf = buf[i+1:] 71 | 72 | if len(f) < 8 { 73 | return nil, nil, fmt.Errorf("iproute entry contains %d fields", len(f)) 74 | } 75 | flags, rt, err := parseRoute(f) 76 | if err != nil { 77 | return nil, nil, err 78 | } 79 | if rt.Dst != nil { 80 | // If gateway for destination 127.0.0.1/32 is 127.0.0.1, set it to nil. 81 | if m, n := rt.Dst.Mask.Size(); n > 0 && m == n && rt.Dst.IP.Equal(rt.Gateway) { 82 | rt.Gateway = nil 83 | } 84 | } 85 | if strings.ContainsRune(flags, '4') { // IPv4 86 | v4 = append(v4, rt) 87 | } 88 | if strings.ContainsRune(flags, '6') { // IPv6 89 | v6 = append(v6, rt) 90 | } 91 | } 92 | return v4, v6, nil 93 | } 94 | 95 | func parseRoute(f []string) (flags string, rt *rtInfo, err error) { 96 | rt = new(rtInfo) 97 | isV4 := strings.ContainsRune(f[3], '4') // flags 98 | 99 | rt.PrefSrc, rt.Src, err = parsePlan9CIDR(f[6], f[7], isV4) 100 | if err != nil { 101 | return "", nil, err 102 | } 103 | _, rt.Dst, err = parsePlan9CIDR(f[0], f[1], isV4) 104 | if err != nil { 105 | return "", nil, err 106 | } 107 | rt.Gateway = net.ParseIP(f[2]) 108 | 109 | n, err := strconv.ParseUint(f[5], 10, 32) 110 | if err != nil { 111 | return "", nil, err 112 | } 113 | rt.InputIface = 0 114 | rt.OutputIface = uint32(n) + 1 // starts at 0, so net package adds 1 115 | rt.Priority = 0 116 | return f[3], rt, nil 117 | } 118 | 119 | func parsePlan9CIDR(addr, mask string, isV4 bool) (net.IP, *net.IPNet, error) { 120 | if len(mask) == 0 || mask[0] != '/' { 121 | return nil, nil, fmt.Errorf("invalid CIDR mask %v", mask) 122 | } 123 | n, err := strconv.ParseUint(mask[1:], 10, 32) 124 | if err != nil { 125 | return nil, nil, err 126 | } 127 | ip := net.ParseIP(addr) 128 | iplen := net.IPv6len 129 | if isV4 { 130 | // Plan 9 uses IPv6 mask for IPv4 addresses 131 | n -= 8 * (net.IPv6len - net.IPv4len) 132 | iplen = net.IPv4len 133 | } 134 | if n == 0 && ip.IsUnspecified() { 135 | return nil, nil, nil 136 | } 137 | m := net.CIDRMask(int(n), 8*iplen) 138 | return ip, &net.IPNet{IP: ip.Mask(m), Mask: m}, nil 139 | } 140 | -------------------------------------------------------------------------------- /common.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | // Originally found in 8 | // https://github.com/google/gopacket/blob/master/routing/routing.go 9 | // - Route selection modified to choose most selective route 10 | // to break ties when route priority is insufficient. 11 | package netroute 12 | 13 | import ( 14 | "bytes" 15 | "errors" 16 | "fmt" 17 | "net" 18 | "strings" 19 | ) 20 | 21 | //lint:file-ignore U1000 structs here used by different build tags 22 | 23 | // rtInfo contains information on a single route. 24 | type rtInfo struct { 25 | Src, Dst *net.IPNet 26 | Gateway, PrefSrc net.IP 27 | // We currently ignore the InputIface. 28 | InputIface, OutputIface uint32 29 | Priority uint32 30 | } 31 | 32 | func (rt rtInfo) IsMoreSpecThan(mostSpecificRt *rtInfo) bool { 33 | if mostSpecificRt == nil { 34 | return true 35 | } 36 | 37 | var candSpec, curSpec int 38 | if rt.Dst != nil { 39 | candSpec, _ = rt.Dst.Mask.Size() 40 | } 41 | if mostSpecificRt.Dst != nil { 42 | curSpec, _ = mostSpecificRt.Dst.Mask.Size() 43 | } 44 | 45 | if candSpec > curSpec { 46 | return true 47 | } else if candSpec < curSpec { 48 | return false 49 | } 50 | 51 | // if all else is equal, prefer a route with a gateway. 52 | if mostSpecificRt.Priority == rt.Priority && rt.Gateway == nil && mostSpecificRt.Gateway != nil { 53 | return false 54 | } 55 | 56 | // Windows and MacOS hasn't metric/priority on rule entry, 57 | // But the interface device has the priority property. 58 | // 59 | // Before we find more correctly way on different OS platform, 60 | // we keep the same rule selecting logical as before which 61 | // is more later more special 62 | return mostSpecificRt.Priority >= rt.Priority 63 | } 64 | 65 | type router struct { 66 | ifaces map[int]net.Interface 67 | addrs map[int]ipAddrs 68 | v4, v6 []*rtInfo 69 | } 70 | 71 | func (r *router) String() string { 72 | strs := []string{"ROUTER", "--- V4 ---"} 73 | for _, route := range r.v4 { 74 | strs = append(strs, fmt.Sprintf("%+v", *route)) 75 | } 76 | strs = append(strs, "--- V6 ---") 77 | for _, route := range r.v6 { 78 | strs = append(strs, fmt.Sprintf("%+v", *route)) 79 | } 80 | return strings.Join(strs, "\n") 81 | } 82 | 83 | type ipAddrs struct { 84 | v4, v6 net.IP 85 | } 86 | 87 | func (r *router) Route(dst net.IP) (iface *net.Interface, gateway, preferredSrc net.IP, err error) { 88 | return r.RouteWithSrc(nil, nil, dst) 89 | } 90 | 91 | func (r *router) RouteWithSrc(input net.HardwareAddr, src, dst net.IP) (iface *net.Interface, gateway, preferredSrc net.IP, err error) { 92 | var ifaceIndex int 93 | switch { 94 | case dst.To4() != nil: 95 | ifaceIndex, gateway, preferredSrc, err = r.route(r.v4, input, src, dst) 96 | case dst.To16() != nil: 97 | ifaceIndex, gateway, preferredSrc, err = r.route(r.v6, input, src, dst) 98 | default: 99 | err = errors.New("IP is not valid as IPv4 or IPv6") 100 | return 101 | } 102 | if err != nil { 103 | return 104 | } 105 | 106 | // Interfaces are 1-indexed, but we store them in a 0-indexed array. 107 | correspondingIface, ok := r.ifaces[ifaceIndex] 108 | if !ok { 109 | err = errors.New("Route refereced unknown interface") 110 | } 111 | iface = &correspondingIface 112 | 113 | if preferredSrc == nil { 114 | switch { 115 | case dst.To4() != nil: 116 | preferredSrc = r.addrs[ifaceIndex].v4 117 | case dst.To16() != nil: 118 | preferredSrc = r.addrs[ifaceIndex].v6 119 | } 120 | } 121 | return 122 | } 123 | 124 | func (r *router) route(routes []*rtInfo, input net.HardwareAddr, src, dst net.IP) (iface int, gateway, preferredSrc net.IP, err error) { 125 | var inputIndex uint32 126 | if input != nil { 127 | for i, iface := range r.ifaces { 128 | if bytes.Equal(input, iface.HardwareAddr) { 129 | // Convert from zero- to one-indexed. 130 | inputIndex = uint32(i + 1) 131 | break 132 | } 133 | } 134 | } 135 | var mostSpecificRt *rtInfo 136 | for _, rt := range routes { 137 | if rt.InputIface != 0 && rt.InputIface != inputIndex { 138 | continue 139 | } 140 | if src != nil && rt.Src != nil && !rt.Src.Contains(src) { 141 | continue 142 | } 143 | if rt.Dst != nil && !rt.Dst.Contains(dst) { 144 | continue 145 | } 146 | if rt.IsMoreSpecThan(mostSpecificRt) { 147 | mostSpecificRt = rt 148 | } 149 | } 150 | if mostSpecificRt != nil { 151 | return int(mostSpecificRt.OutputIface), mostSpecificRt.Gateway, mostSpecificRt.PrefSrc, nil 152 | } 153 | err = fmt.Errorf("no route found for %v", dst) 154 | return 155 | } 156 | -------------------------------------------------------------------------------- /netroute_bsd_test.go: -------------------------------------------------------------------------------- 1 | //go:build darwin || dragonfly || freebsd || netbsd || openbsd 2 | 3 | package netroute 4 | 5 | import ( 6 | "net" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "golang.org/x/net/route" 11 | ) 12 | 13 | func TestToIPAddr(t *testing.T) { 14 | for _, tc := range []struct { 15 | value string 16 | addr route.Addr 17 | mask route.Addr 18 | maskCIDR int 19 | }{ 20 | { 21 | value: "192.168.86.1/32", 22 | addr: &route.Inet4Addr{IP: [4]byte{192, 168, 86, 1}}, 23 | mask: &route.Inet4Addr{IP: [4]byte{255, 255, 255, 255}}, 24 | maskCIDR: 32, 25 | }, 26 | { 27 | value: "192.168.86.1/24", 28 | addr: &route.Inet4Addr{IP: [4]byte{192, 168, 86, 1}}, 29 | mask: &route.Inet4Addr{IP: [4]byte{255, 255, 255, 0}}, 30 | maskCIDR: 24, 31 | }, 32 | { 33 | value: "192.168.86.1/16", 34 | addr: &route.Inet4Addr{IP: [4]byte{192, 168, 86, 1}}, 35 | mask: &route.Inet4Addr{IP: [4]byte{255, 255, 0, 0}}, 36 | maskCIDR: 16, 37 | }, 38 | { 39 | value: "192.168.86.1/8", 40 | addr: &route.Inet4Addr{IP: [4]byte{192, 168, 86, 1}}, 41 | mask: &route.Inet4Addr{IP: [4]byte{255, 0, 0, 0}}, 42 | maskCIDR: 8, 43 | }, 44 | { 45 | value: "192.168.86.1/0", 46 | addr: &route.Inet4Addr{IP: [4]byte{192, 168, 86, 1}}, 47 | mask: &route.Inet4Addr{IP: [4]byte{0, 0, 0, 0}}, 48 | maskCIDR: 0, 49 | }, 50 | { 51 | value: "::1/128", 52 | addr: &route.Inet6Addr{IP: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}, 53 | mask: &route.Inet6Addr{IP: [16]byte{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}}, 54 | maskCIDR: 128, 55 | }, 56 | } { 57 | t.Run(tc.value, func(t *testing.T) { 58 | ip := toIPAddr(tc.addr) 59 | if ip == nil { 60 | t.Fatalf("failed parse err ip: %#v", ip) 61 | } 62 | mask := toIPAddr(tc.mask) 63 | if mask == nil { 64 | t.Fatalf("failed parse mask: %#v", mask) 65 | } 66 | ipn := &net.IPNet{IP: ip, Mask: net.IPMask(mask)} 67 | 68 | l, _ := ipn.Mask.Size() 69 | if l != tc.maskCIDR { 70 | t.Fatalf("maskCIDR %d != %d", l, tc.maskCIDR) 71 | } 72 | 73 | if ipn.String() != tc.value { 74 | t.Fatalf("ipn %s != %s", ipn.String(), tc.value) 75 | } 76 | }) 77 | } 78 | } 79 | 80 | type routeOnBSDTest struct { 81 | dst net.IP 82 | iface *net.Interface 83 | gateway, preferredSrc net.IP 84 | err error 85 | } 86 | 87 | var routeOnBSDTests = []routeOnBSDTest{ 88 | { 89 | dst: net.IP([]byte{127, 0, 0, 1}), 90 | iface: &net.Interface{Name: "lo0"}, 91 | gateway: nil, 92 | preferredSrc: net.IP([]byte{127, 0, 0, 1}), 93 | err: nil, 94 | }, 95 | } 96 | 97 | func TestRouteOnBSD(t *testing.T) { 98 | r, err := New() 99 | if err != nil { 100 | t.Fatal(err) 101 | } 102 | for i, tt := range routeOnBSDTests { 103 | iface, gw, src, err := r.Route(tt.dst) 104 | if tt.err != nil { 105 | assert.NoError(t, err, "test %d: got error, none expected", i) 106 | } 107 | assert.Equal(t, tt.iface.Name, iface.Name, "test %d: expected: %v, got %v", i, tt.iface.Name, iface.Name) 108 | assert.Equal(t, tt.preferredSrc, src, "test %d: expected: %v, got %v", i, tt.preferredSrc, src) 109 | assert.Equal(t, tt.gateway, gw, "test %d: expected: %v, got %v", i, tt.gateway, gw) 110 | } 111 | } 112 | 113 | type ipToIfIndexTest struct { 114 | ip net.IP 115 | index int 116 | } 117 | 118 | var ipToIfIndexTests = []ipToIfIndexTest{ 119 | { 120 | net.IPv4(127, 0, 0, 1), 121 | 1, 122 | }, 123 | { 124 | net.IPv4(127, 0, 0, 100), 125 | -1, 126 | }, 127 | } 128 | 129 | func TestIPToIfIndex(t *testing.T) { 130 | for i, tt := range ipToIfIndexTests { 131 | ifIndex, err := ipToIfIndex(tt.ip) 132 | if tt.index >= 1 { 133 | assert.NoError(t, err, "test %d: got error, none expected", i) 134 | assert.GreaterOrEqual(t, ifIndex, 1) 135 | continue 136 | } 137 | assert.LessOrEqual(t, ifIndex, 0) 138 | } 139 | } 140 | 141 | type toRouteAddrTest struct { 142 | ip net.IP 143 | addr route.Addr 144 | passing bool 145 | } 146 | 147 | var toRouteAddrTests = []toRouteAddrTest{ 148 | { 149 | net.IPv4(127, 0, 0, 1), 150 | &route.Inet4Addr{IP: [4]byte{127, 0, 0, 1}}, 151 | true, 152 | }, 153 | { 154 | net.IP([]byte{127, 0, 0, 1}), 155 | &route.Inet4Addr{IP: [4]byte{127, 0, 0, 1}}, 156 | true, 157 | }, 158 | { 159 | net.IPv4(127, 0, 0, 1), 160 | &route.Inet4Addr{IP: [4]byte{127, 0, 0, 0}}, 161 | false, 162 | }, 163 | } 164 | 165 | func TestToRoueAddr(t *testing.T) { 166 | for i, tt := range toRouteAddrTests { 167 | a := toRouteAddr(tt.ip) 168 | if tt.passing { 169 | assert.Equal(t, tt.addr, a, "test %d: expected: %v, got %v", i, tt.addr, a) 170 | continue 171 | } 172 | assert.NotEqual(t, tt.addr, a, "test %d: did not expect: %v, but got %v", i, tt.addr, a) 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /netroute_windows.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | 3 | package netroute 4 | 5 | // Implementation Warning: mapping of the correct interface ID and index is not 6 | // hooked up. 7 | // Reference: 8 | // https://docs.microsoft.com/en-us/windows/win32/api/netioapi/nf-netioapi-getbestroute2 9 | import ( 10 | "bytes" 11 | "encoding/binary" 12 | "fmt" 13 | "net" 14 | "unsafe" 15 | 16 | "golang.org/x/sys/windows" 17 | ) 18 | 19 | var ( 20 | modiphlpapi = windows.NewLazyDLL("iphlpapi.dll") 21 | procGetBestRoute2 = modiphlpapi.NewProc("GetBestRoute2") 22 | ) 23 | 24 | type NetLUID uint64 25 | 26 | type AddressPrefix struct { 27 | *windows.RawSockaddrAny 28 | PrefixLength byte 29 | } 30 | 31 | type RouteProtocol uint32 // MIB_IPFORWARD_PROTO 32 | 33 | // https://docs.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_ipforward_row2 34 | type mib_row2 struct { 35 | luid NetLUID 36 | index uint32 37 | destinationPrefix *AddressPrefix 38 | nextHop *windows.RawSockaddrAny 39 | prefixLength byte 40 | lifetime uint32 41 | preferredLifetime uint32 42 | metric uint32 43 | protocol RouteProtocol 44 | loopback byte 45 | autoconfigured byte 46 | publish byte 47 | immortal byte 48 | age uint32 49 | origin byte 50 | } 51 | 52 | func callBestRoute(source, dest net.IP) (*mib_row2, net.IP, error) { 53 | sourceAddr, _, _ := sockaddrToAny(ipAndZoneToSockaddr(source, "")) 54 | destAddr, _, _ := sockaddrToAny(ipAndZoneToSockaddr(dest, "")) 55 | bestRoute := make([]byte, 512) 56 | bestSource := make([]byte, 116) 57 | 58 | err := getBestRoute2(nil, 0, sourceAddr, destAddr, 0, bestRoute, bestSource) 59 | if err != nil { 60 | return nil, nil, err 61 | } 62 | 63 | // interpret best route and best source. 64 | route, err := parseRoute(bestRoute) 65 | if err != nil { 66 | return nil, nil, err 67 | } 68 | 69 | // per https://docs.microsoft.com/en-us/windows/win32/api/netioapi/ns-netioapi-mib_ipforward_row2 70 | // If the route is to a local loopback address or an IP address on the local link, the next hop is unspecified (all zeros) 71 | if isZero(route.nextHop) { 72 | route.nextHop = nil 73 | } 74 | 75 | var bestSourceRaw windows.RawSockaddrAny 76 | bestSourceRaw.Addr.Family = binary.LittleEndian.Uint16(bestSource[0:2]) 77 | copyInto(bestSourceRaw.Addr.Data[:], bestSource[2:16]) 78 | copyInto(bestSourceRaw.Pad[:], bestSource[16:]) 79 | addr, _ := bestSourceRaw.Sockaddr() 80 | bestSrc, _ := sockaddrToIPAndZone(addr) 81 | 82 | return route, bestSrc, nil 83 | } 84 | 85 | func copyInto(dst []int8, src []byte) { 86 | for i, b := range src { 87 | dst[i] = int8(b) 88 | } 89 | } 90 | 91 | func isZero(addr *windows.RawSockaddrAny) bool { 92 | for _, b := range addr.Addr.Data { 93 | if b != 0 { 94 | return false 95 | } 96 | } 97 | for _, b := range addr.Pad { 98 | if b != 0 { 99 | return false 100 | } 101 | } 102 | return true 103 | } 104 | 105 | func parseRoute(mib []byte) (*mib_row2, error) { 106 | var route mib_row2 107 | var err error 108 | 109 | route.luid = NetLUID(binary.LittleEndian.Uint64(mib[0:])) 110 | route.index = binary.LittleEndian.Uint32(mib[8:]) 111 | idx := 0 112 | route.destinationPrefix, idx, err = readDestPrefix(mib, 12) 113 | if err != nil { 114 | return nil, err 115 | } 116 | route.nextHop, idx, err = readSockAddr(mib, idx) 117 | if err != nil { 118 | return nil, err 119 | } 120 | route.prefixLength = mib[idx] 121 | idx += 1 122 | route.lifetime = binary.LittleEndian.Uint32(mib[idx : idx+4]) 123 | idx += 4 124 | route.preferredLifetime = binary.LittleEndian.Uint32(mib[idx : idx+4]) 125 | idx += 4 126 | route.metric = binary.LittleEndian.Uint32(mib[idx : idx+4]) 127 | idx += 4 128 | route.protocol = RouteProtocol(binary.LittleEndian.Uint32(mib[idx : idx+4])) 129 | idx += 4 130 | route.loopback = mib[idx] 131 | idx += 1 132 | route.autoconfigured = mib[idx] 133 | idx += 1 134 | route.publish = mib[idx] 135 | idx += 1 136 | route.immortal = mib[idx] 137 | idx += 1 138 | route.age = binary.LittleEndian.Uint32(mib[idx : idx+4]) 139 | idx += 4 140 | route.origin = mib[idx] 141 | 142 | return &route, err 143 | } 144 | 145 | func readDestPrefix(buffer []byte, idx int) (*AddressPrefix, int, error) { 146 | sock, idx2, err := readSockAddr(buffer, idx) 147 | if err != nil { 148 | return nil, 0, err 149 | } 150 | pfixLen := buffer[idx2] 151 | if idx2-idx > 32 { 152 | return nil, idx, fmt.Errorf("Unexpectedly large internal sockaddr struct") 153 | } 154 | return &AddressPrefix{sock, pfixLen}, idx + 32, nil 155 | } 156 | 157 | func readSockAddr(buffer []byte, idx int) (*windows.RawSockaddrAny, int, error) { 158 | var rsa windows.RawSockaddrAny 159 | rsa.Addr.Family = binary.LittleEndian.Uint16(buffer[idx : idx+2]) 160 | if rsa.Addr.Family == windows.AF_INET || rsa.Addr.Family == windows.AF_UNSPEC { 161 | copyInto(rsa.Addr.Data[:], buffer[idx+2:idx+16]) 162 | return &rsa, idx + 16, nil 163 | } else if rsa.Addr.Family == windows.AF_INET6 { 164 | copyInto(rsa.Addr.Data[:], buffer[idx+2:idx+16]) 165 | copyInto(rsa.Pad[:], buffer[idx+16:idx+28]) 166 | return &rsa, idx + 28, nil 167 | } else { 168 | return nil, 0, fmt.Errorf("Unknown windows addr family %d", rsa.Addr.Family) 169 | } 170 | } 171 | 172 | func getBestRoute2(interfaceLuid *NetLUID, interfaceIndex uint32, sourceAddress, destinationAddress *windows.RawSockaddrAny, addressSortOptions uint32, bestRoute []byte, bestSourceAddress []byte) (errcode error) { 173 | r0, _, _ := procGetBestRoute2.Call( 174 | uintptr(unsafe.Pointer(interfaceLuid)), 175 | uintptr(interfaceIndex), 176 | uintptr(unsafe.Pointer(sourceAddress)), 177 | uintptr(unsafe.Pointer(destinationAddress)), 178 | uintptr(addressSortOptions), 179 | uintptr(unsafe.Pointer(&bestRoute[0])), 180 | uintptr(unsafe.Pointer(&bestSourceAddress[0]))) 181 | if r0 != 0 { 182 | errcode = windows.Errno(r0) 183 | } 184 | return 185 | } 186 | 187 | func getIface(index uint32) *net.Interface { 188 | var ifRow windows.MibIfRow 189 | ifRow.Index = index 190 | err := windows.GetIfEntry(&ifRow) 191 | if err != nil { 192 | return nil 193 | } 194 | 195 | physAddrLen := int(ifRow.PhysAddrLen) 196 | if len(ifRow.PhysAddr) < physAddrLen && physAddrLen >= 0 { 197 | physAddrLen = len(ifRow.PhysAddr) 198 | } 199 | physAddr := ifRow.PhysAddr[:physAddrLen] 200 | 201 | ifaces, err := net.Interfaces() 202 | if err != nil { 203 | return nil 204 | } 205 | for _, iface := range ifaces { 206 | if bytes.Equal(iface.HardwareAddr, physAddr) { 207 | return &iface 208 | } 209 | } 210 | return nil 211 | } 212 | 213 | type winRouter struct{} 214 | 215 | func (r *winRouter) Route(dst net.IP) (iface *net.Interface, gateway, preferredSrc net.IP, err error) { 216 | return r.RouteWithSrc(nil, nil, dst) 217 | } 218 | 219 | func (r *winRouter) RouteWithSrc(input net.HardwareAddr, src, dst net.IP) (iface *net.Interface, gateway, preferredSrc net.IP, err error) { 220 | route, pref, err := callBestRoute(src, dst) 221 | if err != nil { 222 | return nil, nil, nil, err 223 | } 224 | iface = getIface(route.index) 225 | 226 | if route.nextHop == nil || route.nextHop.Addr.Family == 0 /* AF_UNDEF */ { 227 | return iface, nil, pref, nil 228 | } 229 | addr, err := route.nextHop.Sockaddr() 230 | if err != nil { 231 | return nil, nil, nil, err 232 | } 233 | nextHop, _ := sockaddrToIPAndZone(addr) 234 | 235 | return iface, nextHop, pref, nil 236 | } 237 | 238 | func New() (Router, error) { 239 | rtr := &winRouter{} 240 | return rtr, nil 241 | } 242 | -------------------------------------------------------------------------------- /netroute_linux.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | //go:build linux 8 | 9 | // Generate a local routing table structure following the code at 10 | // https://github.com/google/gopacket/blob/master/routing/routing.go 11 | 12 | package netroute 13 | 14 | import ( 15 | "bytes" 16 | "encoding/binary" 17 | "errors" 18 | "fmt" 19 | "net" 20 | "os" 21 | "slices" 22 | "sync/atomic" 23 | "syscall" 24 | "unsafe" 25 | ) 26 | 27 | var nlSequence uint32 28 | 29 | type linuxRouter struct{} 30 | 31 | func New() (Router, error) { 32 | return &linuxRouter{}, nil 33 | } 34 | 35 | // Route implements Router. 36 | func (l *linuxRouter) Route(dst net.IP) (iface *net.Interface, gateway net.IP, preferredSrc net.IP, err error) { 37 | return l.RouteWithSrc(nil, nil, dst) 38 | } 39 | 40 | // RouteWithSrc implements Router. 41 | func (l *linuxRouter) RouteWithSrc(input net.HardwareAddr, src net.IP, dst net.IP) (iface *net.Interface, gateway net.IP, preferredSrc net.IP, err error) { 42 | if dst == nil || dst.IsUnspecified() { 43 | return nil, nil, nil, errors.New("destination IP must be specified") 44 | } 45 | 46 | // trim bytes if this is a v4 addr 47 | if v4 := dst.To4(); v4 != nil { 48 | dst = v4 49 | } 50 | 51 | dstFamily := addressFamily(dst) 52 | if src != nil && !src.IsUnspecified() { 53 | srcFamily := addressFamily(src) 54 | if srcFamily != dstFamily { 55 | return nil, nil, nil, fmt.Errorf("source %q and destination %q use different address families", src.String(), dst.String()) 56 | } 57 | } 58 | 59 | var oif int 60 | if len(input) > 0 { 61 | ifaces, err := net.Interfaces() 62 | if err != nil { 63 | return nil, nil, nil, fmt.Errorf("list interfaces: %w", err) 64 | } 65 | for i := range ifaces { 66 | iface := ifaces[i] 67 | if bytes.Equal(iface.HardwareAddr, input) { 68 | oif = iface.Index 69 | break 70 | } 71 | } 72 | if oif == 0 { 73 | return nil, nil, nil, fmt.Errorf("no interface with address %s found", input.String()) 74 | } 75 | } 76 | 77 | fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_DGRAM, syscall.NETLINK_ROUTE) 78 | if err != nil { 79 | return nil, nil, nil, fmt.Errorf("open netlink socket: %w", err) 80 | } 81 | defer syscall.Close(fd) 82 | 83 | sa := &syscall.SockaddrNetlink{Family: syscall.AF_NETLINK} 84 | if err := syscall.Bind(fd, sa); err != nil { 85 | return nil, nil, nil, fmt.Errorf("bind netlink socket: %w", err) 86 | } 87 | 88 | seq := atomic.AddUint32(&nlSequence, 1) 89 | request, err := buildRouteRequest(dstFamily, dst, src, oif, seq, uint32(os.Getpid())) 90 | if err != nil { 91 | return nil, nil, nil, err 92 | } 93 | 94 | if err := syscall.Sendto(fd, request, 0, &syscall.SockaddrNetlink{Family: syscall.AF_NETLINK}); err != nil { 95 | return nil, nil, nil, fmt.Errorf("send netlink request: %w", err) 96 | } 97 | 98 | route, err := readRouteResponse(fd, seq) 99 | if err != nil { 100 | return nil, nil, nil, err 101 | } 102 | 103 | outIface, err := net.InterfaceByIndex(int(route.OutputIface)) 104 | if err != nil { 105 | return nil, nil, nil, fmt.Errorf("get interface by index: %w", err) 106 | } 107 | 108 | if len(input) > 0 && iface != nil && len(iface.HardwareAddr) > 0 && !bytes.Equal(iface.HardwareAddr, input) { 109 | return nil, nil, nil, fmt.Errorf("route resolved to interface %s (%s), expected %s", iface.Name, iface.HardwareAddr, input) 110 | } 111 | 112 | var srcIP net.IP 113 | if len(route.PrefSrc) > 0 && !route.PrefSrc.IsUnspecified() { 114 | srcIP = route.PrefSrc 115 | } else if route.Src != nil { 116 | srcIP = route.Src.IP 117 | } else { 118 | return nil, nil, nil, fmt.Errorf("no source IP found") 119 | } 120 | 121 | // copyIP so we don't leak a reference to our working buffer 122 | return outIface, copyIP(route.Gateway), copyIP(srcIP), nil 123 | } 124 | 125 | func buildRouteRequest(family int, dst []byte, src []byte, oif int, seq, pid uint32) ([]byte, error) { 126 | bodyBuf := new(bytes.Buffer) 127 | 128 | rtm := syscall.RtMsg{ 129 | Family: uint8(family), 130 | Dst_len: uint8(len(dst) * 8), 131 | Src_len: uint8(len(src) * 8), 132 | Table: syscall.RT_TABLE_UNSPEC, 133 | } 134 | if err := binary.Write(bodyBuf, binary.NativeEndian, rtm); err != nil { 135 | return nil, fmt.Errorf("marshal rtmsg: %w", err) 136 | } 137 | if len(dst) > 0 { 138 | if err := writeRouteAttr(bodyBuf, syscall.RTA_DST, dst); err != nil { 139 | return nil, err 140 | } 141 | } 142 | if len(src) > 0 { 143 | if err := writeRouteAttr(bodyBuf, syscall.RTA_SRC, src); err != nil { 144 | return nil, err 145 | } 146 | } 147 | if oif != 0 { 148 | oifBytes := make([]byte, 4) 149 | binary.NativeEndian.PutUint32(oifBytes, uint32(oif)) 150 | if err := writeRouteAttr(bodyBuf, syscall.RTA_OIF, oifBytes); err != nil { 151 | return nil, err 152 | } 153 | } 154 | 155 | header := syscall.NlMsghdr{ 156 | Len: uint32(syscall.NLMSG_HDRLEN + bodyBuf.Len()), 157 | Type: uint16(syscall.RTM_GETROUTE), 158 | Flags: uint16(syscall.NLM_F_REQUEST), 159 | Seq: seq, 160 | Pid: pid, 161 | } 162 | 163 | msgBuf := new(bytes.Buffer) 164 | if err := binary.Write(msgBuf, binary.NativeEndian, header); err != nil { 165 | return nil, fmt.Errorf("marshal nlmsghdr: %w", err) 166 | } 167 | if _, err := msgBuf.Write(bodyBuf.Bytes()); err != nil { 168 | return nil, fmt.Errorf("assemble netlink request: %w", err) 169 | } 170 | return msgBuf.Bytes(), nil 171 | } 172 | 173 | func writeRouteAttr(buf *bytes.Buffer, attrType uint16, payload []byte) error { 174 | attrLen := uint16(syscall.SizeofRtAttr + len(payload)) 175 | attr := syscall.RtAttr{ 176 | Len: attrLen, 177 | Type: attrType, 178 | } 179 | if err := binary.Write(buf, binary.NativeEndian, attr); err != nil { 180 | return fmt.Errorf("marshal rtattr: %w", err) 181 | } 182 | if _, err := buf.Write(payload); err != nil { 183 | return fmt.Errorf("write rtattr payload: %w", err) 184 | } 185 | 186 | const nlMsghdrLenAlignment = 4 187 | padLen := alignTo(attrLen, nlMsghdrLenAlignment) - int(attrLen) 188 | if padLen > 0 { 189 | _, _ = buf.Write(make([]byte, padLen)) 190 | } 191 | return nil 192 | } 193 | 194 | func alignTo(length uint16, alignment int) int { 195 | l := int(length) 196 | return (l + alignment - 1) & ^(alignment - 1) 197 | } 198 | 199 | func readRouteResponse(fd int, seq uint32) (*rtInfo, error) { 200 | buf := make([]byte, 1<<16) 201 | for { 202 | n, _, err := syscall.Recvfrom(fd, buf, 0) 203 | if err != nil { 204 | return nil, fmt.Errorf("receive netlink response: %w", err) 205 | } 206 | 207 | msgs, err := syscall.ParseNetlinkMessage(buf[:n]) 208 | if err != nil { 209 | return nil, fmt.Errorf("parse netlink response: %w", err) 210 | } 211 | 212 | for _, m := range msgs { 213 | if m.Header.Seq != seq { 214 | continue 215 | } 216 | switch m.Header.Type { 217 | case syscall.NLMSG_ERROR: 218 | if err := parseNetlinkError(m.Data); err != nil { 219 | return nil, fmt.Errorf("netlink error: %w", err) 220 | } 221 | case syscall.NLMSG_DONE: 222 | return nil, errors.New("route lookup returned no result") 223 | case syscall.RTM_NEWROUTE: 224 | var routeInfo rtInfo 225 | if err := routeInfo.parse(&m); err != nil { 226 | return nil, err 227 | } 228 | if routeInfo.Dst == nil && routeInfo.Src == nil && routeInfo.Gateway == nil { 229 | continue 230 | } 231 | return &routeInfo, nil 232 | } 233 | } 234 | } 235 | } 236 | 237 | func parseNetlinkError(data []byte) error { 238 | if len(data) < syscall.SizeofNlMsgerr { 239 | return fmt.Errorf("short netlink error payload: %d", len(data)) 240 | } 241 | var msg syscall.NlMsgerr 242 | reader := bytes.NewReader(data[:syscall.SizeofNlMsgerr]) 243 | if err := binary.Read(reader, binary.NativeEndian, &msg); err != nil { 244 | return fmt.Errorf("decode nlmsgerr: %w", err) 245 | } 246 | if msg.Error == 0 { 247 | return nil 248 | } 249 | 250 | // Error is negative errno or 0 for acknowledgements 251 | return syscall.Errno(-msg.Error) 252 | } 253 | 254 | func (routeInfo *rtInfo) parse(msg *syscall.NetlinkMessage) error { 255 | rt := (*syscall.RtMsg)(unsafe.Pointer(&msg.Data[0])) 256 | if rt.Family != syscall.AF_INET && rt.Family != syscall.AF_INET6 { 257 | return errors.New("unsupported address family") 258 | } 259 | 260 | attrs, err := syscall.ParseNetlinkRouteAttr(msg) 261 | if err != nil { 262 | return err 263 | } 264 | for _, attr := range attrs { 265 | switch attr.Attr.Type { 266 | case syscall.RTA_DST: 267 | routeInfo.Dst = &net.IPNet{ 268 | IP: net.IP(attr.Value), 269 | Mask: net.CIDRMask(int(rt.Dst_len), len(attr.Value)*8), 270 | } 271 | case syscall.RTA_SRC: 272 | routeInfo.Src = &net.IPNet{ 273 | // Copy the IP so we don't keep a reference to this buffer 274 | IP: net.IP(attr.Value), 275 | Mask: net.CIDRMask(int(rt.Src_len), len(attr.Value)*8), 276 | } 277 | case syscall.RTA_GATEWAY: 278 | routeInfo.Gateway = net.IP(attr.Value) 279 | case syscall.RTA_PREFSRC: 280 | routeInfo.PrefSrc = net.IP(attr.Value) 281 | case syscall.RTA_IIF: 282 | routeInfo.InputIface = *(*uint32)(unsafe.Pointer(&attr.Value[0])) 283 | case syscall.RTA_OIF: 284 | routeInfo.OutputIface = *(*uint32)(unsafe.Pointer(&attr.Value[0])) 285 | case syscall.RTA_PRIORITY: 286 | routeInfo.Priority = *(*uint32)(unsafe.Pointer(&attr.Value[0])) 287 | } 288 | } 289 | return nil 290 | } 291 | 292 | func addressFamily(ip net.IP) int { 293 | if ip.To4() != nil { 294 | return syscall.AF_INET 295 | } 296 | return syscall.AF_INET6 297 | } 298 | 299 | func copyIP(ip net.IP) net.IP { 300 | if len(ip) == 0 { 301 | return nil 302 | } 303 | out := slices.Clone(ip) 304 | if v4 := out.To4(); v4 != nil { 305 | out = v4 306 | } 307 | return out 308 | } 309 | -------------------------------------------------------------------------------- /netroute_bsd.go: -------------------------------------------------------------------------------- 1 | // Copyright 2012 Google, Inc. All rights reserved. 2 | // 3 | // Use of this source code is governed by a BSD-style license 4 | // that can be found in the LICENSE file in the root of the source 5 | // tree. 6 | 7 | //go:build darwin || dragonfly || freebsd || netbsd || openbsd 8 | 9 | // This is a BSD import for the routing structure initially found in 10 | // https://github.com/google/gopacket/blob/master/routing/routing.go 11 | // RIB parsing follows the BSD route format described in 12 | // https://github.com/freebsd/freebsd/blob/master/sys/net/route.h 13 | package netroute 14 | 15 | import ( 16 | "errors" 17 | "fmt" 18 | "net" 19 | "os" 20 | "sync/atomic" 21 | "syscall" 22 | "time" 23 | 24 | "golang.org/x/net/route" 25 | "golang.org/x/sys/unix" 26 | ) 27 | 28 | const ( 29 | RTF_IFSCOPE = 0x1000000 30 | ROUTE_MSGFILTER = 1 31 | ) 32 | 33 | type bsdRouter struct { 34 | id uintptr 35 | seq atomic.Uint32 36 | } 37 | 38 | // toIPAddr converts a route.Addr to a net.IP. 39 | // Returns nil if the address type is not recognized. 40 | func toIPAddr(a route.Addr) net.IP { 41 | switch t := a.(type) { 42 | case *route.Inet4Addr: 43 | return t.IP[:] 44 | case *route.Inet6Addr: 45 | return t.IP[:] 46 | default: 47 | return nil 48 | } 49 | } 50 | 51 | // toRouteAddr takes a net.IP and returns the corresponding route.Addr. 52 | // Returns nil if the IP is empty or has an invalid length. 53 | // IPv4 addresses are converted to route.Inet4Addr and IPv6 to route.Inet6Addr. 54 | func toRouteAddr(ip net.IP) route.Addr { 55 | if len(ip) == 0 { 56 | return nil 57 | } 58 | 59 | if len(ip) != net.IPv4len && len(ip) != net.IPv6len { 60 | return nil 61 | } 62 | if p4 := ip.To4(); len(p4) == net.IPv4len { 63 | return &route.Inet4Addr{IP: [4]byte(p4)} 64 | } 65 | return &route.Inet6Addr{IP: [16]byte(ip)} 66 | } 67 | 68 | // ipToIfIndex takes an IP and returns the index of the interface with the given IP assigned. 69 | // Returns an error if no interface is found with the specified IP address. 70 | func ipToIfIndex(ip net.IP) (int, error) { 71 | ifaces, err := net.Interfaces() 72 | if err != nil { 73 | return -1, fmt.Errorf("failed to get interfaces: %w", err) 74 | } 75 | for _, iface := range ifaces { 76 | addrs, err := iface.Addrs() 77 | if err != nil { 78 | continue 79 | } 80 | for _, addr := range addrs { 81 | inet, ok := addr.(*net.IPNet) 82 | if !ok { 83 | continue 84 | } 85 | if inet.IP.Equal(ip) { 86 | return iface.Index, nil 87 | } 88 | } 89 | } 90 | return -1, fmt.Errorf("no interface found for IP: %s", ip) 91 | } 92 | 93 | // macToIfIndex takes a MAC address and returns the index of the interface with the matching hardware address. 94 | // Returns an error if no interface is found with the specified MAC address. 95 | func macToIfIndex(hwAddr net.HardwareAddr) (int, error) { 96 | ifaces, err := net.Interfaces() 97 | if err != nil { 98 | return -1, fmt.Errorf("failed to get interfaces: %w", err) 99 | } 100 | for _, iface := range ifaces { 101 | if hwAddr.String() == iface.HardwareAddr.String() { 102 | return iface.Index, nil 103 | } 104 | } 105 | return -1, fmt.Errorf("no interface found for MAC: %s", hwAddr.String()) 106 | } 107 | 108 | // getIfIndex determines the interface index based on the provided MAC address and/or IP address. 109 | // If both are provided, it ensures they resolve to the same interface. 110 | // Returns -1 if neither MAC nor IP is provided, or an error if they resolve to different interfaces. 111 | func getIfIndex(MACAddr net.HardwareAddr, ip net.IP) (int, error) { 112 | ipIndex := -1 113 | macIndex := -1 114 | var err error 115 | if ip == nil && MACAddr == nil { 116 | return -1, nil 117 | } 118 | 119 | if ip != nil { 120 | ipIndex, err = ipToIfIndex(ip) 121 | if err != nil { 122 | return -1, fmt.Errorf("failed to find interface with IP: %s", ip.String()) 123 | } 124 | } 125 | 126 | if MACAddr != nil { 127 | macIndex, err = macToIfIndex(MACAddr) 128 | if err != nil { 129 | return -1, fmt.Errorf("failed to find interface with MAC: %s", MACAddr.String()) 130 | } 131 | } 132 | 133 | switch { 134 | case (ipIndex >= 0 && macIndex >= 0) && (macIndex != ipIndex): 135 | return -1, fmt.Errorf("given MAC address and source IP resolve to different interfaces") 136 | case (ipIndex >= 0 && macIndex >= 0) && (macIndex == ipIndex): 137 | return ipIndex, nil 138 | case ipIndex >= 0: 139 | return ipIndex, nil 140 | case macIndex >= 0: 141 | return macIndex, nil 142 | default: 143 | return -1, fmt.Errorf("no index found for given ip and/or MAC address") 144 | } 145 | } 146 | 147 | // composeRouteMsg creates a RTM_GET RouteMessage for querying the routing table. 148 | // It takes the process ID, optional MAC address, optional source IP, and destination IP. 149 | // The function determines the appropriate interface index if MAC or source IP is provided. 150 | func composeRouteMsg(id uintptr, seq int, MACAddr net.HardwareAddr, src, dst net.IP) (*route.RouteMessage, error) { 151 | dstAddr := toRouteAddr(dst) 152 | if dstAddr == nil { 153 | return nil, fmt.Errorf("failed to parse dst: %#v", dst) 154 | } 155 | 156 | msg := &route.RouteMessage{ 157 | Version: syscall.RTM_VERSION, 158 | Type: unix.RTM_GET, 159 | ID: id, 160 | Seq: seq, 161 | Addrs: []route.Addr{ 162 | dstAddr, 163 | nil, 164 | nil, 165 | nil, 166 | &route.LinkAddr{}, 167 | }, 168 | } 169 | 170 | ifIndex, err := getIfIndex(MACAddr, src) 171 | if err != nil { 172 | return nil, err 173 | } 174 | 175 | if ifIndex >= 0 { 176 | msg.Flags = RTF_IFSCOPE 177 | msg.Index = ifIndex 178 | } 179 | 180 | return msg, nil 181 | } 182 | 183 | func (r *bsdRouter) getSeq() int { 184 | return int(r.seq.Add(1)) 185 | } 186 | 187 | // getRouteMsgReply takes an RTM_GET RouteMessage and returns reply (RouteMessage) 188 | func getRouteMsgReply(msg *route.RouteMessage) (*route.RouteMessage, error) { 189 | if msg.Type != syscall.RTM_GET { 190 | return nil, errors.New("message type is not RTM_GET") 191 | } 192 | 193 | fd, err := getRouteFD() 194 | if err != nil { 195 | return nil, err 196 | } 197 | defer unix.Close(fd) 198 | 199 | err = writeMsg(fd, msg) 200 | if err != nil { 201 | return nil, err 202 | } 203 | 204 | // Read the response message 205 | return readMsg(msg.ID, msg.Seq, fd) 206 | } 207 | 208 | // getRouteFD opens a routing socket. 209 | // Returns the file descriptor for the socket or an error if the socket cannot be created. 210 | func getRouteFD() (int, error) { 211 | fd, err := unix.Socket(unix.AF_ROUTE, unix.SOCK_RAW, unix.AF_UNSPEC) 212 | if err != nil { 213 | scope := "route socket - open" 214 | return -1, annotateUnixError(err, scope) 215 | } 216 | 217 | return fd, nil 218 | } 219 | 220 | // writeMsg marshals and writes a RouteMessage to the specified file descriptor. 221 | // Returns an error if marshaling fails or if the write operation fails. 222 | func writeMsg(fd int, msg *route.RouteMessage) error { 223 | buf, err := msg.Marshal() 224 | if err != nil { 225 | return fmt.Errorf("invalid route message given: %w", err) 226 | } 227 | 228 | if _, err = unix.Write(fd, buf); err != nil { 229 | scope := "route socket - write" 230 | return annotateUnixError(err, scope) 231 | } 232 | 233 | return nil 234 | } 235 | 236 | // readMsg reads a response from the routing socket and returns the matching RouteMessage. 237 | // It spawns a goroutine to read from the socket and filters messages based on the provided ID and sequence number. 238 | // The function includes a 10-second timeout to prevent indefinite blocking. 239 | func readMsg(id uintptr, seq, fd int) (*route.RouteMessage, error) { 240 | type readResult struct { 241 | msg *route.RouteMessage 242 | err error 243 | } 244 | 245 | // Create a channel to receive the result 246 | resultCh := make(chan readResult, 1) 247 | 248 | go func() { 249 | var rb [2 << 10]byte 250 | for { 251 | n, err := unix.Read(fd, rb[:]) 252 | if err != nil { 253 | scope := "route socket - read" 254 | resultCh <- readResult{ 255 | err: annotateUnixError(err, scope), 256 | } 257 | return 258 | } 259 | 260 | // Parse response messages 261 | msgs, err := route.ParseRIB(route.RIBTypeRoute, rb[:n]) 262 | if err != nil { 263 | resultCh <- readResult{ 264 | err: fmt.Errorf("failed to parse messages: %w", err), 265 | } 266 | return 267 | } 268 | 269 | if len(msgs) != 1 { 270 | resultCh <- readResult{ 271 | err: fmt.Errorf("unexpected number of messages received: %d", len(msgs)), 272 | } 273 | return 274 | } 275 | 276 | msg, ok := msgs[0].(*route.RouteMessage) 277 | // confirm it is a reply to our query 278 | if !ok || (id != msg.ID && seq != msg.Seq) { 279 | continue 280 | } 281 | 282 | resultCh <- readResult{ 283 | msg: msg, 284 | } 285 | 286 | return 287 | } 288 | }() 289 | 290 | select { 291 | case result := <-resultCh: 292 | return result.msg, result.err 293 | case <-time.After(10 * time.Second): 294 | return nil, fmt.Errorf("route socket - read: timedout") 295 | } 296 | } 297 | 298 | func annotateUnixError(err error, scope string) error { 299 | var msg string 300 | switch err { 301 | case nil: 302 | return nil 303 | case unix.ESRCH: 304 | msg = "route not found" 305 | // socket errors 306 | case unix.EACCES: 307 | msg = "permission denied" 308 | case unix.EMFILE: 309 | msg = "file system table full" 310 | case unix.ENOBUFS: 311 | msg = "insufficient buffer space" 312 | case unix.EPERM: 313 | msg = "insufficient privileges" 314 | case unix.EPROTOTYPE: 315 | msg = "socket type not supported" 316 | // read errors 317 | case unix.EBADF: 318 | msg = "invalid socket" 319 | case unix.ECONNRESET: 320 | msg = "socket closed" 321 | case unix.EFAULT: 322 | msg = "invalid buffer" 323 | case unix.EIO: 324 | msg = "I/O error" 325 | case unix.EBUSY: 326 | msg = "failed to read from file descriptor" 327 | case unix.EINVAL: 328 | msg = "invalid file descriptor" 329 | case unix.EAGAIN: 330 | msg = "no data available, try again later" 331 | default: // unexpected system error; fatal 332 | msg = "unexpected error" 333 | } 334 | if scope != "" { 335 | msg = scope + ": " + msg 336 | } 337 | return fmt.Errorf("%s: %w", msg, err) 338 | } 339 | 340 | // Route implements the routing.Router interface to find the best route to the destination IP. 341 | // Returns the outgoing interface, gateway IP, preferred source IP, and any error encountered. 342 | func (r *bsdRouter) Route(dst net.IP) (iface *net.Interface, gateway, preferredSrc net.IP, err error) { 343 | return r.RouteWithSrc(nil, nil, dst) 344 | } 345 | 346 | // RouteWithSrc extends the Route method to allow specifying a source MAC address and IP. 347 | // This enables more precise routing decisions when multiple interfaces are available. 348 | // Returns the outgoing interface, gateway IP, preferred source IP, and any error encountered. 349 | func (r *bsdRouter) RouteWithSrc(MACAddr net.HardwareAddr, src, dst net.IP) (iface *net.Interface, gateway, preferredSrc net.IP, err error) { 350 | msg, err := composeRouteMsg(r.id, r.getSeq(), MACAddr, src, dst) 351 | if err != nil { 352 | return 353 | } 354 | 355 | var reply *route.RouteMessage 356 | if reply, err = getRouteMsgReply(msg); err != nil { 357 | return 358 | } 359 | 360 | if iface, err = net.InterfaceByIndex(reply.Index); err != nil { 361 | return 362 | } 363 | 364 | preferredSrc = toIPAddr(reply.Addrs[5]) 365 | 366 | isGatewayRequired := dst.String() != preferredSrc.String() 367 | if !isGatewayRequired { 368 | return 369 | } 370 | 371 | gateway = toIPAddr(reply.Addrs[1]) 372 | 373 | return 374 | } 375 | 376 | // New returns a new instance of a BSD-specific routing.Router implementation. 377 | // The router is stateless and uses the routing tables of the host system. 378 | func New() (Router, error) { 379 | r := &bsdRouter{} 380 | r.id = uintptr(os.Getpid()) 381 | 382 | return r, nil 383 | } 384 | --------------------------------------------------------------------------------