payload_cmsg.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 !plan9,!solaris,!windows
  5. package ipv4
  6. import (
  7. "net"
  8. "syscall"
  9. )
  10. // ReadFrom reads a payload of the received IPv4 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, syscall.EINVAL
  17. }
  18. oob := newControlMessage(&c.rawOpt)
  19. var oobn int
  20. switch c := c.PacketConn.(type) {
  21. case *net.UDPConn:
  22. if n, oobn, _, src, err = c.ReadMsgUDP(b, oob); err != nil {
  23. return 0, nil, nil, err
  24. }
  25. case *net.IPConn:
  26. nb := make([]byte, maxHeaderLen+len(b))
  27. if n, oobn, _, src, err = c.ReadMsgIP(nb, oob); err != nil {
  28. return 0, nil, nil, err
  29. }
  30. hdrlen := int(nb[0]&0x0f) << 2
  31. copy(b, nb[hdrlen:])
  32. n -= hdrlen
  33. default:
  34. return 0, nil, nil, errInvalidConnType
  35. }
  36. if cm, err = parseControlMessage(oob[:oobn]); err != nil {
  37. return 0, nil, nil, err
  38. }
  39. if cm != nil {
  40. cm.Src = netAddrToIP4(src)
  41. }
  42. return
  43. }
  44. // WriteTo writes a payload of the IPv4 datagram, to the destination
  45. // address dst through the endpoint c, copying the payload from b. It
  46. // returns the number of bytes written. The control message cm allows
  47. // the datagram path and the outgoing interface to be specified.
  48. // Currently only Darwin and Darwin support this. The cm may be nil if
  49. // 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, syscall.EINVAL
  53. }
  54. oob := marshalControlMessage(cm)
  55. if dst == nil {
  56. return 0, errMissingAddress
  57. }
  58. switch c := c.PacketConn.(type) {
  59. case *net.UDPConn:
  60. n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr))
  61. case *net.IPConn:
  62. n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr))
  63. default:
  64. return 0, errInvalidConnType
  65. }
  66. if err != nil {
  67. return 0, err
  68. }
  69. return
  70. }