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.
 
 
 

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