packet_go1_8.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2012 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 !go1.9
  5. package ipv4
  6. import "net"
  7. func (c *packetHandler) readFrom(b []byte) (h *Header, p []byte, cm *ControlMessage, err error) {
  8. c.rawOpt.RLock()
  9. oob := NewControlMessage(c.rawOpt.cflags)
  10. c.rawOpt.RUnlock()
  11. n, nn, _, src, err := c.ReadMsgIP(b, oob)
  12. if err != nil {
  13. return nil, nil, nil, err
  14. }
  15. var hs []byte
  16. if hs, p, err = slicePacket(b[:n]); err != nil {
  17. return nil, nil, nil, err
  18. }
  19. if h, err = ParseHeader(hs); err != nil {
  20. return nil, nil, nil, err
  21. }
  22. if nn > 0 {
  23. cm = new(ControlMessage)
  24. if err := cm.Parse(oob[:nn]); err != nil {
  25. return nil, nil, nil, err
  26. }
  27. }
  28. if src != nil && cm != nil {
  29. cm.Src = src.IP
  30. }
  31. return
  32. }
  33. func (c *packetHandler) writeTo(h *Header, p []byte, cm *ControlMessage) error {
  34. oob := cm.Marshal()
  35. wh, err := h.Marshal()
  36. if err != nil {
  37. return err
  38. }
  39. dst := new(net.IPAddr)
  40. if cm != nil {
  41. if ip := cm.Dst.To4(); ip != nil {
  42. dst.IP = ip
  43. }
  44. }
  45. if dst.IP == nil {
  46. dst.IP = h.Dst
  47. }
  48. wh = append(wh, p...)
  49. _, _, err = c.WriteMsgIP(wh, oob, dst)
  50. return err
  51. }