|
|
|
|
|
by Hikikomori
383 days ago
|
|
Cool! I did something similar when I wanted to learn Go, but did my own parsers instead of using gopacket, I would recommend doing that yourself if you want to learn more low level stuff. How I parsed IP for example: type Addr [4]uint8
func (ip Addr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
}
type Hdr struct {
Version uint8
IHL uint8
DSCP uint8
ECN uint8
Length uint16
Id uint16
Flags uint8
Fragoffset uint16
TTL uint8
Protocol uint8
Checksum uint16
Src Addr
Dst Addr
}
func (hdr *Hdr) Parse(d []byte) error {
hdr.Version = uint8(d[0] >> 4)
hdr.IHL = uint8(d[0] & 0x0f)
hdr.DSCP = uint8(d[1] >> 6)
hdr.ECN = uint8(d[1] & 0x03)
hdr.Length = uint16(binary.BigEndian.Uint16(d[2:4]))
hdr.Id = uint16(binary.BigEndian.Uint16(d[4:6]))
hdr.Flags = uint8(d[6] >> 5)
hdr.Fragoffset = uint16(binary.BigEndian.Uint16(d[6:8])) & 0x1fff
hdr.TTL = d[8]
hdr.Protocol = d[9]
hdr.Checksum = uint16(binary.BigEndian.Uint16(d[10:12]))
hdr.Src = Addr{d[12], d[13], d[14], d[15]}
hdr.Dst = Addr{d[16], d[17], d[18], d[19]}
if hdr.IHL > 5 {
fmt.Println("extra options detected") // TODO: support for extra options
}
return nil
}
|
|
Yeah, I’m currently using gopacket mainly to get something working fast, but I’ve been thinking about writing my own parsers from scratch to understand the protocols better.
Your Hdr example is really clean — definitely saving this as reference! I love how direct and readable it is.
I’ll definitely try going lower level when I revisit the packet layer logic. Thanks again for the nudge