Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

70 lignes
2.0 KiB

  1. // Copyright 2014 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 icmp
  5. import (
  6. "encoding/binary"
  7. "net"
  8. "runtime"
  9. "golang.org/x/net/internal/socket"
  10. "golang.org/x/net/ipv4"
  11. )
  12. // freebsdVersion is set in sys_freebsd.go.
  13. // See http://www.freebsd.org/doc/en/books/porters-handbook/freebsd-versions.html.
  14. var freebsdVersion uint32
  15. // ParseIPv4Header returns the IPv4 header of the IPv4 packet that
  16. // triggered an ICMP error message.
  17. // This is found in the Data field of the ICMP error message body.
  18. //
  19. // The provided b must be in the format used by a raw ICMP socket on
  20. // the local system.
  21. // This may differ from the wire format, and the format used by a raw
  22. // IP socket, depending on the system.
  23. //
  24. // To parse an IPv6 header, use ipv6.ParseHeader.
  25. func ParseIPv4Header(b []byte) (*ipv4.Header, error) {
  26. if len(b) < ipv4.HeaderLen {
  27. return nil, errHeaderTooShort
  28. }
  29. hdrlen := int(b[0]&0x0f) << 2
  30. if hdrlen > len(b) {
  31. return nil, errBufferTooShort
  32. }
  33. h := &ipv4.Header{
  34. Version: int(b[0] >> 4),
  35. Len: hdrlen,
  36. TOS: int(b[1]),
  37. ID: int(binary.BigEndian.Uint16(b[4:6])),
  38. FragOff: int(binary.BigEndian.Uint16(b[6:8])),
  39. TTL: int(b[8]),
  40. Protocol: int(b[9]),
  41. Checksum: int(binary.BigEndian.Uint16(b[10:12])),
  42. Src: net.IPv4(b[12], b[13], b[14], b[15]),
  43. Dst: net.IPv4(b[16], b[17], b[18], b[19]),
  44. }
  45. switch runtime.GOOS {
  46. case "darwin":
  47. h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4]))
  48. case "freebsd":
  49. if freebsdVersion >= 1000000 {
  50. h.TotalLen = int(binary.BigEndian.Uint16(b[2:4]))
  51. } else {
  52. h.TotalLen = int(socket.NativeEndian.Uint16(b[2:4]))
  53. }
  54. default:
  55. h.TotalLen = int(binary.BigEndian.Uint16(b[2:4]))
  56. }
  57. h.Flags = ipv4.HeaderFlags(h.FragOff&0xe000) >> 13
  58. h.FragOff = h.FragOff & 0x1fff
  59. if hdrlen-ipv4.HeaderLen > 0 {
  60. h.Options = make([]byte, hdrlen-ipv4.HeaderLen)
  61. copy(h.Options, b[ipv4.HeaderLen:])
  62. }
  63. return h, nil
  64. }