UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » how to handle structure alignment for networking properly?

#1 2011-08-07 04:33 PM

thinking
Member
Registered: 2005-09-15
Posts: 103

how to handle structure alignment for networking properly?

hi all,

im working on a simple networking application where i ran into structure alignment problem.
to keep it simple i had a structure like this:

struct somename{
    uint8_t val1;
    uint8_t val2;
    uint8_t val3;

    uin16_t val4;
....
};

between val3 and val4, gcc inserted a byte for alignment - which make sense
as far as i know different compilers handle this different
for example, different compiler implementations or different architectures and such
so my questions are the following:
o) what's the minimum i can be sure the implementation will handle properly?
for example on a 64bit architecture does it append also just 1 byte to be 4byte aligned or will it add 5bytes to be 8byte aligned?
you see, this is a basic quesiton im not sure of how alignment works. can i be sure that everything will be aligned to 4 bytes, also on a 8/16bit microcontroller?

o) how is such a problem solved properly?
i mean how does a networked base game handle this problem?
adding #pragma or __attribute's to prevent alignment isnt very portable
or is this just not that kind of problem which can be solved portable?

btw: using htonl can be assumend to be known

thx for help

Offline

#2 2011-08-08 01:14 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,847
Website

Re: how to handle structure alignment for networking properly?

Offline

#3 2011-08-16 07:24 PM

thinking
Member
Registered: 2005-09-15
Posts: 103

Re: how to handle structure alignment for networking properly?

thank you, Rob
your practical knowledge is very helpful

i also noticed that gcc provides an option -Wpadded which causes a warning if a structure is padded
this can be helpful for experimentation to get a better understanding of how it works

Offline

  • Index
  • » C
  • » how to handle structure alignment for networking properly?

Board footer

Powered by FluxBB