route_linux.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package nl
  2. import (
  3. "syscall"
  4. "unsafe"
  5. )
  6. type RtMsg struct {
  7. syscall.RtMsg
  8. }
  9. func NewRtMsg() *RtMsg {
  10. return &RtMsg{
  11. RtMsg: syscall.RtMsg{
  12. Table: syscall.RT_TABLE_MAIN,
  13. Scope: syscall.RT_SCOPE_UNIVERSE,
  14. Protocol: syscall.RTPROT_BOOT,
  15. Type: syscall.RTN_UNICAST,
  16. },
  17. }
  18. }
  19. func NewRtDelMsg() *RtMsg {
  20. return &RtMsg{
  21. RtMsg: syscall.RtMsg{
  22. Table: syscall.RT_TABLE_MAIN,
  23. Scope: syscall.RT_SCOPE_NOWHERE,
  24. },
  25. }
  26. }
  27. func (msg *RtMsg) Len() int {
  28. return syscall.SizeofRtMsg
  29. }
  30. func DeserializeRtMsg(b []byte) *RtMsg {
  31. return (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0]))
  32. }
  33. func (msg *RtMsg) Serialize() []byte {
  34. return (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]
  35. }
  36. type RtNexthop struct {
  37. syscall.RtNexthop
  38. Children []NetlinkRequestData
  39. }
  40. func DeserializeRtNexthop(b []byte) *RtNexthop {
  41. return (*RtNexthop)(unsafe.Pointer(&b[0:syscall.SizeofRtNexthop][0]))
  42. }
  43. func (msg *RtNexthop) Len() int {
  44. if len(msg.Children) == 0 {
  45. return syscall.SizeofRtNexthop
  46. }
  47. l := 0
  48. for _, child := range msg.Children {
  49. l += rtaAlignOf(child.Len())
  50. }
  51. l += syscall.SizeofRtNexthop
  52. return rtaAlignOf(l)
  53. }
  54. func (msg *RtNexthop) Serialize() []byte {
  55. length := msg.Len()
  56. msg.RtNexthop.Len = uint16(length)
  57. buf := make([]byte, length)
  58. copy(buf, (*(*[syscall.SizeofRtNexthop]byte)(unsafe.Pointer(msg)))[:])
  59. next := rtaAlignOf(syscall.SizeofRtNexthop)
  60. if len(msg.Children) > 0 {
  61. for _, child := range msg.Children {
  62. childBuf := child.Serialize()
  63. copy(buf[next:], childBuf)
  64. next += rtaAlignOf(len(childBuf))
  65. }
  66. }
  67. return buf
  68. }