ipv4.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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/ipv4"
  10. )
  11. // ParseIPv4Header parses b as an IPv4 header of ICMP error message
  12. // invoking packet, which is contained in ICMP error message.
  13. func ParseIPv4Header(b []byte) (*ipv4.Header, error) {
  14. if len(b) < ipv4.HeaderLen {
  15. return nil, errHeaderTooShort
  16. }
  17. hdrlen := int(b[0]&0x0f) << 2
  18. if hdrlen > len(b) {
  19. return nil, errBufferTooShort
  20. }
  21. h := &ipv4.Header{
  22. Version: int(b[0] >> 4),
  23. Len: hdrlen,
  24. TOS: int(b[1]),
  25. ID: int(binary.BigEndian.Uint16(b[4:6])),
  26. FragOff: int(binary.BigEndian.Uint16(b[6:8])),
  27. TTL: int(b[8]),
  28. Protocol: int(b[9]),
  29. Checksum: int(binary.BigEndian.Uint16(b[10:12])),
  30. Src: net.IPv4(b[12], b[13], b[14], b[15]),
  31. Dst: net.IPv4(b[16], b[17], b[18], b[19]),
  32. }
  33. switch runtime.GOOS {
  34. case "darwin":
  35. h.TotalLen = int(nativeEndian.Uint16(b[2:4]))
  36. case "freebsd":
  37. if freebsdVersion >= 1000000 {
  38. h.TotalLen = int(binary.BigEndian.Uint16(b[2:4]))
  39. } else {
  40. h.TotalLen = int(nativeEndian.Uint16(b[2:4]))
  41. }
  42. default:
  43. h.TotalLen = int(binary.BigEndian.Uint16(b[2:4]))
  44. }
  45. h.Flags = ipv4.HeaderFlags(h.FragOff&0xe000) >> 13
  46. h.FragOff = h.FragOff & 0x1fff
  47. if hdrlen-ipv4.HeaderLen > 0 {
  48. h.Options = make([]byte, hdrlen-ipv4.HeaderLen)
  49. copy(h.Options, b[ipv4.HeaderLen:])
  50. }
  51. return h, nil
  52. }