payload_cmsg_go1_8.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2013 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 ipv6
  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. if n, nn, _, src, err = c.ReadMsgIP(b, oob); err != nil {
  20. return 0, nil, nil, err
  21. }
  22. default:
  23. return 0, nil, nil, &net.OpError{Op: "read", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Err: errInvalidConnType}
  24. }
  25. if nn > 0 {
  26. cm = new(ControlMessage)
  27. if err = cm.Parse(oob[:nn]); err != nil {
  28. return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}
  29. }
  30. }
  31. if cm != nil {
  32. cm.Src = netAddrToIP16(src)
  33. }
  34. return
  35. }
  36. func (c *payloadHandler) writeTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) {
  37. oob := cm.Marshal()
  38. if dst == nil {
  39. return 0, &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errMissingAddress}
  40. }
  41. switch c := c.PacketConn.(type) {
  42. case *net.UDPConn:
  43. n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr))
  44. case *net.IPConn:
  45. n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr))
  46. default:
  47. return 0, &net.OpError{Op: "write", Net: c.LocalAddr().Network(), Source: c.LocalAddr(), Addr: opAddr(dst), Err: errInvalidConnType}
  48. }
  49. return
  50. }