Packet parsing in Go

581 views
Skip to first unread message

Rakesh K R

unread,
Apr 21, 2020, 12:08:22 PM4/21/20
to golang-nuts
Hi,
I am new to Go and I am trying to parse the network packets received.
In C, we used to typecast this array of uint8_t to predefined structure. Is there a way I can do this similarly in Go? or any better approach to do this in Go?
i.e. I need to parse the packet to store them to respective l2/l3/l4 and mdns header structures

Jan Mercl

unread,
Apr 21, 2020, 2:15:17 PM4/21/20
to Rakesh K R, golang-nuts
On Tue, Apr 21, 2020 at 6:08 PM Rakesh K R <rakesh...@gmail.com> wrote:

> In C, we used to typecast this array of uint8_t to predefined structure.

Go has no casts. Regardless, one can do something similar using
unsafe. But then - how it's planned to deal with the situation when
the machine endianess does not match the order of the bytes in the
packet?

Rakesh K R

unread,
Apr 21, 2020, 2:28:53 PM4/21/20
to Jan Mercl, golang-nuts
Application is supposed to run on docker and base image for this docker is fixed. i.e ubuntu 18 always.

Looks like I need to parse slice of bytes one by one. gopacket has support for packet parsing but it dont support dlna packets.
Any pointers apart from this will be helpful 
--
null

Manlio Perillo

unread,
Apr 21, 2020, 4:12:11 PM4/21/20
to golang-nuts

Note that https://golang.org/pkg/encoding/binary/ only support big endian and little endian, but not native endian.
This blog post may be useful:

If you need to support bad written protocols using native endian, see https://github.com/golang/net/blob/master/internal/socket/sys.go.

Manlio

wagner riffel

unread,
Apr 22, 2020, 4:10:20 AM4/22/20
to Rakesh K R, Jan Mercl, golang-nuts
On Tue, 21 Apr 2020 02:22:37 -0700 (PDT)
Rakesh K R <rakesh...@gmail.com> wrote:

> In C, we used to typecast this array of uint8_t to predefined
> structure.
>

This is very bad even for a C program, as soon as you dereference
pointer to such structure it's an undefined behavior, and not portable
even on LE architectures, definitely such dereference would lead to a
runtime crash on arm cpus, ubuntu or docker wouldn't change anything,
also, the c compiler might add padding to your structure, which can
make such parser give the wrong answer even on architectures that allows
unaligned addressing. (unless you're non-standard compiler extensions
to avoid that)

Thus, even on C, the correct and portable way to parse an uint8_t array
is also going bytes one by one, i recommend you stick with the
"encoding/binary" package, it will do the right thing.

BR.

—wagner
Reply all
Reply to author
Forward
0 new messages