2022-08-17 15:46:49 +00:00
|
|
|
package packet
|
|
|
|
|
2024-11-19 20:44:24 +00:00
|
|
|
import (
|
|
|
|
"github.com/google/gopacket"
|
|
|
|
)
|
2022-08-17 15:46:49 +00:00
|
|
|
|
|
|
|
var (
|
|
|
|
serializeOpts = gopacket.SerializeOptions{
|
|
|
|
FixLengths: true,
|
|
|
|
ComputeChecksums: true,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// RawPacket represents a raw packet or one encoded by Encoder
|
|
|
|
type RawPacket struct {
|
|
|
|
Data []byte
|
|
|
|
}
|
|
|
|
|
|
|
|
type Encoder struct {
|
|
|
|
// buf is reusable because SerializeLayers calls the Clear method before each encoding
|
|
|
|
buf gopacket.SerializeBuffer
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewEncoder() *Encoder {
|
|
|
|
return &Encoder{
|
|
|
|
buf: gopacket.NewSerializeBuffer(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-19 20:44:24 +00:00
|
|
|
func (e *Encoder) Encode(packet Packet) (RawPacket, error) {
|
2022-08-17 15:46:49 +00:00
|
|
|
encodedLayers, err := packet.EncodeLayers()
|
|
|
|
if err != nil {
|
|
|
|
return RawPacket{}, err
|
|
|
|
}
|
|
|
|
if err := gopacket.SerializeLayers(e.buf, serializeOpts, encodedLayers...); err != nil {
|
|
|
|
return RawPacket{}, err
|
|
|
|
}
|
|
|
|
return RawPacket{
|
|
|
|
Data: e.buf.Bytes(),
|
|
|
|
}, nil
|
|
|
|
}
|