Skip to content

Instantly share code, notes, and snippets.

@ion1
Created April 12, 2010 10:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ion1/363428 to your computer and use it in GitHub Desktop.
Save ion1/363428 to your computer and use it in GitHub Desktop.
Parsing IPv4/UDP/NTP packets in Erlang
parse_ip (Packet) ->
case Packet of
<<4:4, HeaderLength:4, _DiffServ:8, _Length:16, _Identification:16,
_Flags:3, _FragOffset:13, _TTL:8, Protocol:8, _HeaderChecksum:16,
SrcAddr:32/bits, DstAddr:32/bits, OptionsAndData/bytes>>
->
OptionsLength = HeaderLength*32-160,
<<_Options:OptionsLength, Data/bytes>> = OptionsAndData,
case Protocol of
17 ->
parse_udp (SrcAddr, DstAddr, Data);
_ ->
ignored end;
_ ->
ignored end.
parse_udp (SrcAddr, DstAddr, Packet) ->
case Packet of
<<SrcPort:16, DstPort:16, _Length:16, _Checksum:16, Data/bytes>> ->
if
SrcPort =:= 123 orelse DstPort =:= 123 ->
parse_ntp ({SrcAddr, SrcPort}, {DstAddr, DstPort}, Data);
true ->
ignored end;
_ ->
ignored end.
parse_ntp (Src, Dst, Packet) ->
case Packet of
<<_LeapIndicator:2, _Version:3, Mode:3, _Rest/bytes>> ->
{ntp, {Src, Dst, ntp_mode_atom (Mode)}};
_ ->
ignored end.
ntp_mode_atom (1) -> symmetric_active;
ntp_mode_atom (2) -> symmetric_passive;
ntp_mode_atom (3) -> client;
ntp_mode_atom (4) -> server;
ntp_mode_atom (5) -> broadcast;
ntp_mode_atom (_) -> invalid.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment