Base code for packet handling