control_pktinfo.go 894 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright 2014 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 linux
  5. package ipv4
  6. import (
  7. "syscall"
  8. "unsafe"
  9. "golang.org/x/net/internal/iana"
  10. )
  11. func marshalPacketInfo(b []byte, cm *ControlMessage) []byte {
  12. m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
  13. m.Level = iana.ProtocolIP
  14. m.Type = sysIP_PKTINFO
  15. m.SetLen(syscall.CmsgLen(sysSizeofInetPktinfo))
  16. if cm != nil {
  17. pi := (*sysInetPktinfo)(unsafe.Pointer(&b[syscall.CmsgLen(0)]))
  18. if ip := cm.Src.To4(); ip != nil {
  19. copy(pi.Spec_dst[:], ip)
  20. }
  21. if cm.IfIndex > 0 {
  22. pi.setIfindex(cm.IfIndex)
  23. }
  24. }
  25. return b[syscall.CmsgSpace(sysSizeofInetPktinfo):]
  26. }
  27. func parsePacketInfo(cm *ControlMessage, b []byte) {
  28. pi := (*sysInetPktinfo)(unsafe.Pointer(&b[0]))
  29. cm.IfIndex = int(pi.Ifindex)
  30. cm.Dst = pi.Addr[:]
  31. }