packet.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. package ipv4
  5. import (
  6. "net"
  7. "golang.org/x/net/internal/socket"
  8. )
  9. // BUG(mikio): On Windows, the ReadFrom and WriteTo methods of RawConn
  10. // are not implemented.
  11. // A packetHandler represents the IPv4 datagram handler.
  12. type packetHandler struct {
  13. *net.IPConn
  14. *socket.Conn
  15. rawOpt
  16. }
  17. func (c *packetHandler) ok() bool { return c != nil && c.IPConn != nil && c.Conn != nil }
  18. // ReadFrom reads an IPv4 datagram from the endpoint c, copying the
  19. // datagram into b. It returns the received datagram as the IPv4
  20. // header h, the payload p and the control message cm.
  21. func (c *packetHandler) ReadFrom(b []byte) (h *Header, p []byte, cm *ControlMessage, err error) {
  22. if !c.ok() {
  23. return nil, nil, nil, errInvalidConn
  24. }
  25. return c.readFrom(b)
  26. }
  27. func slicePacket(b []byte) (h, p []byte, err error) {
  28. if len(b) < HeaderLen {
  29. return nil, nil, errHeaderTooShort
  30. }
  31. hdrlen := int(b[0]&0x0f) << 2
  32. return b[:hdrlen], b[hdrlen:], nil
  33. }
  34. // WriteTo writes an IPv4 datagram through the endpoint c, copying the
  35. // datagram from the IPv4 header h and the payload p. The control
  36. // message cm allows the datagram path and the outgoing interface to be
  37. // specified. Currently only Darwin and Linux support this. The cm
  38. // may be nil if control of the outgoing datagram is not required.
  39. //
  40. // The IPv4 header h must contain appropriate fields that include:
  41. //
  42. // Version = <must be specified>
  43. // Len = <must be specified>
  44. // TOS = <must be specified>
  45. // TotalLen = <must be specified>
  46. // ID = platform sets an appropriate value if ID is zero
  47. // FragOff = <must be specified>
  48. // TTL = <must be specified>
  49. // Protocol = <must be specified>
  50. // Checksum = platform sets an appropriate value if Checksum is zero
  51. // Src = platform sets an appropriate value if Src is nil
  52. // Dst = <must be specified>
  53. // Options = optional
  54. func (c *packetHandler) WriteTo(h *Header, p []byte, cm *ControlMessage) error {
  55. if !c.ok() {
  56. return errInvalidConn
  57. }
  58. return c.writeTo(h, p, cm)
  59. }