header.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 ipv6
  5. import (
  6. "fmt"
  7. "net"
  8. )
  9. const (
  10. Version = 6 // protocol version
  11. HeaderLen = 40 // header length
  12. )
  13. // A Header represents an IPv6 base header.
  14. type Header struct {
  15. Version int // protocol version
  16. TrafficClass int // traffic class
  17. FlowLabel int // flow label
  18. PayloadLen int // payload length
  19. NextHeader int // next header
  20. HopLimit int // hop limit
  21. Src net.IP // source address
  22. Dst net.IP // destination address
  23. }
  24. func (h *Header) String() string {
  25. if h == nil {
  26. return "<nil>"
  27. }
  28. return fmt.Sprintf("ver=%d tclass=%#x flowlbl=%#x payloadlen=%d nxthdr=%d hoplim=%d src=%v dst=%v", h.Version, h.TrafficClass, h.FlowLabel, h.PayloadLen, h.NextHeader, h.HopLimit, h.Src, h.Dst)
  29. }
  30. // ParseHeader parses b as an IPv6 base header.
  31. func ParseHeader(b []byte) (*Header, error) {
  32. if len(b) < HeaderLen {
  33. return nil, errHeaderTooShort
  34. }
  35. h := &Header{
  36. Version: int(b[0]) >> 4,
  37. TrafficClass: int(b[0]&0x0f)<<4 | int(b[1])>>4,
  38. FlowLabel: int(b[1]&0x0f)<<16 | int(b[2])<<8 | int(b[3]),
  39. PayloadLen: int(b[4])<<8 | int(b[5]),
  40. NextHeader: int(b[6]),
  41. HopLimit: int(b[7]),
  42. }
  43. h.Src = make(net.IP, net.IPv6len)
  44. copy(h.Src, b[8:24])
  45. h.Dst = make(net.IP, net.IPv6len)
  46. copy(h.Dst, b[24:40])
  47. return h, nil
  48. }