You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
2.2 KiB

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