payload_cmsg_go1_8.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. // +build darwin dragonfly freebsd linux netbsd openbsd solaris
  6. package ipv4
  7. import "net"
  8. func (c *payloadHandler) readFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) {
  9. c.rawOpt.RLock()
  10. oob := NewControlMessage(c.rawOpt.cflags)
  11. c.rawOpt.RUnlock()
  12. var nn int
  13. switch c := c.PacketConn.(type) {
  14. case *net.UDPConn:
  15. if n, nn, _, src, err = c.ReadMsgUDP(b, oob); err != nil {
  16. return 0, nil, nil, err
  17. }
  18. case *net.IPConn:
  19. nb := make([]byte, maxHeaderLen+len(b))
  20. if n, nn, _, src, err = c.ReadMsgIP(nb, oob); err != nil {
  21. return 0, nil, nil, err
  22. }
  23. hdrlen := int(nb[0]&0x0f) << 2
  24. copy(b, nb[hdrlen:])
  25. n -= hdrlen
  26. default:
  27. return 0, nil, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Err: errInvalidConnType}
  28. }
  29. if nn > 0 {
  30. cm = new(ControlMessage)
  31. if err = cm.Parse(oob[:nn]); err != nil {
  32. return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}
  33. }
  34. }
  35. if cm != nil {
  36. cm.Src = netAddrToIP4(src)
  37. }
  38. return
  39. }
  40. func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) {
  41. oob := cm.Marshal()
  42. if dst == nil {
  43. return 0, &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errMissingAddress}
  44. }
  45. switch c := c.PacketConn.(type) {
  46. case *net.UDPConn:
  47. n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr))
  48. case *net.IPConn:
  49. n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr))
  50. default:
  51. return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Addr: opAddr(dst), Err: errInvalidConnType}
  52. }
  53. return
  54. }