route.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // +build darwin dragonfly freebsd netbsd openbsd
  5. // Package route provides basic functions for the manipulation of
  6. // packet routing facilities on BSD variants.
  7. //
  8. // The package supports any version of Darwin, any version of
  9. // DragonFly BSD, FreeBSD 7 through 11, NetBSD 6 and above, and
  10. // OpenBSD 5.6 and above.
  11. package route
  12. import (
  13. "errors"
  14. "os"
  15. "syscall"
  16. )
  17. var (
  18. errUnsupportedMessage = errors.New("unsupported message")
  19. errMessageMismatch = errors.New("message mismatch")
  20. errMessageTooShort = errors.New("message too short")
  21. errInvalidMessage = errors.New("invalid message")
  22. errInvalidAddr = errors.New("invalid address")
  23. )
  24. // A RouteMessage represents a message conveying an address prefix, a
  25. // nexthop address and an output interface.
  26. type RouteMessage struct {
  27. Version int // message version
  28. Type int // message type
  29. Flags int // route flags
  30. Index int // interface index when atatched
  31. Addrs []Addr // addresses
  32. extOff int // offset of header extension
  33. raw []byte // raw message
  34. }
  35. // A RIBType reprensents a type of routing information base.
  36. type RIBType int
  37. const (
  38. RIBTypeRoute RIBType = syscall.NET_RT_DUMP
  39. RIBTypeInterface RIBType = syscall.NET_RT_IFLIST
  40. )
  41. // FetchRIB fetches a routing information base from the operating
  42. // system.
  43. //
  44. // The provided af must be an address family.
  45. //
  46. // The provided arg must be a RIBType-specific argument.
  47. // When RIBType is related to routes, arg might be a set of route
  48. // flags. When RIBType is related to network interfaces, arg might be
  49. // an interface index or a set of interface flags. In most cases, zero
  50. // means a wildcard.
  51. func FetchRIB(af int, typ RIBType, arg int) ([]byte, error) {
  52. mib := [6]int32{sysCTL_NET, sysAF_ROUTE, 0, int32(af), int32(typ), int32(arg)}
  53. n := uintptr(0)
  54. if err := sysctl(mib[:], nil, &n, nil, 0); err != nil {
  55. return nil, os.NewSyscallError("sysctl", err)
  56. }
  57. if n == 0 {
  58. return nil, nil
  59. }
  60. b := make([]byte, n)
  61. if err := sysctl(mib[:], &b[0], &n, nil, 0); err != nil {
  62. return nil, os.NewSyscallError("sysctl", err)
  63. }
  64. return b[:n], nil
  65. }