control_pktinfo.go 945 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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 solaris
  5. package ipv4
  6. import (
  7. "net"
  8. "unsafe"
  9. "golang.org/x/net/internal/iana"
  10. "golang.org/x/net/internal/socket"
  11. )
  12. func marshalPacketInfo(b []byte, cm *ControlMessage) []byte {
  13. m := socket.ControlMessage(b)
  14. m.MarshalHeader(iana.ProtocolIP, sysIP_PKTINFO, sizeofInetPktinfo)
  15. if cm != nil {
  16. pi := (*inetPktinfo)(unsafe.Pointer(&m.Data(sizeofInetPktinfo)[0]))
  17. if ip := cm.Src.To4(); ip != nil {
  18. copy(pi.Spec_dst[:], ip)
  19. }
  20. if cm.IfIndex > 0 {
  21. pi.setIfindex(cm.IfIndex)
  22. }
  23. }
  24. return m.Next(sizeofInetPktinfo)
  25. }
  26. func parsePacketInfo(cm *ControlMessage, b []byte) {
  27. pi := (*inetPktinfo)(unsafe.Pointer(&b[0]))
  28. cm.IfIndex = int(pi.Ifindex)
  29. if len(cm.Dst) < net.IPv4len {
  30. cm.Dst = make(net.IP, net.IPv4len)
  31. }
  32. copy(cm.Dst, pi.Addr[:])
  33. }