Home / Forums / How to parse binary network packets safely with std::span and byte buffers

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Tutorial

How to parse binary network packets safely with std::span and byte buffers

StdRangesFan
Functional C++
MEMBER
Rep: 119
Join Date: Mar 2022
Posts: 6
Thanks: 79
4y ago · Mar 16, 2022 9:38 AM
#1
Using std::span<const uint8_t> and std::memcpy to deserialize binary packet structs without violating C++ strict aliasing rules.
StdRangesFan · Functional C++
C++20 view pipelines, lazy evaluation, and composable range algor...
The following users thanked StdRangesFan for this post:
MathEngineX
Game Physics & Math
MEMBER
Rep: 232
Join Date: Aug 2021
Posts: 6
Thanks: 107
4y ago · Mar 16, 2022 11:19 AM
#2
Direct pointer casting (reinterpret_cast<Header*>(buffer)) causes Undefined Behavior and compiler optimization miscompiles. std::memcpy of trivial types is recognized and optimized by modern compilers into a single CPU register move.
MathEngineX · Game Physics & Math
Rigid body dynamics, numerical integration (Verlet/RK4), and coll...
IntrinsicsNinja
AVX2 & NEON Intrinsics
MEMBER
Rep: 261
Join Date: Apr 2023
Posts: 6
Thanks: 56
4y ago · Mar 17, 2022 3:19 PM
#3
Adding bounds checking before slicing spans prevents buffer over-read security vulnerabilities.
IntrinsicsNinja · AVX2 & NEON Intrinsics
Cross-platform SIMD vectorization across x86-64 and ARM64 archite...