payload_cmsg.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 aix darwin dragonfly freebsd linux netbsd openbsd solaris
  5. package ipv6
  6. import (
  7. "net"
  8. "golang.org/x/net/internal/socket"
  9. )
  10. // ReadFrom reads a payload of the received IPv6 datagram, from the
  11. // endpoint c, copying the payload into b. It returns the number of
  12. // bytes copied into b, the control message cm and the source address
  13. // src of the received datagram.
  14. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) {
  15. if !c.ok() {
  16. return 0, nil, nil, errInvalidConn
  17. }
  18. c.rawOpt.RLock()
  19. m := socket.Message{
  20. Buffers: [][]byte{b},
  21. OOB: NewControlMessage(c.rawOpt.cflags),
  22. }
  23. c.rawOpt.RUnlock()
  24. switch c.PacketConn.(type) {
  25. case *net.UDPConn:
  26. if err := c.RecvMsg(&m, 0); err != nil {
  27. return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}
  28. }
  29. case *net.IPConn:
  30. if err := c.RecvMsg(&m, 0); err != nil {
  31. return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}
  32. }
  33. default:
  34. return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: errInvalidConnType}
  35. }
  36. if m.NN > 0 {
  37. cm = new(ControlMessage)
  38. if err := cm.Parse(m.OOB[:m.NN]); err != nil {
  39. return 0, nil, nil, &net.OpError{Op: "read", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Err: err}
  40. }
  41. cm.Src = netAddrToIP16(m.Addr)
  42. }
  43. return m.N, cm, m.Addr, nil
  44. }
  45. // WriteTo writes a payload of the IPv6 datagram, to the destination
  46. // address dst through the endpoint c, copying the payload from b. It
  47. // returns the number of bytes written. The control message cm allows
  48. // the IPv6 header fields and the datagram path to be specified. The
  49. // cm may be nil if control of the outgoing datagram is not required.
  50. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) {
  51. if !c.ok() {
  52. return 0, errInvalidConn
  53. }
  54. m := socket.Message{
  55. Buffers: [][]byte{b},
  56. OOB: cm.Marshal(),
  57. Addr: dst,
  58. }
  59. err = c.SendMsg(&m, 0)
  60. if err != nil {
  61. err = &net.OpError{Op: "write", Net: c.PacketConn.LocalAddr().Network(), Source: c.PacketConn.LocalAddr(), Addr: opAddr(dst), Err: err}
  62. }
  63. return m.N, err
  64. }