Network byte order conversion of structures in C language

Asked 1 years ago, Updated 1 years ago, 40 views

There are the following structures:
Regardless of big endian or little endian,
I would like to write a code that can be converted (or type defined) to a network byte order.
[Structure]

structure sample {
  unsigned short a:12;
  unsigned short b:2;
  unsigned short c:2;
};

↓ Is there no problem with this?

structure sample val={300,1,2};
htons(uint16_t)val);

Or, if I define it as follows, is it okay not to convert it with htons()?

structure sample {
# if__BYTE_ORDER ==_LITTLE_ENDIAN
  unsigned short a1:8; first half of /*a */
  unsigned short c:2;
  unsigned short b:2;
  unsigned short a2:4; later in /*a */
#endif
# if__BYTE_ORDER ==__BIG_ENDIAN
  /* If it's a Big Endian, can I just play it? */
  unsigned short a:12;
  unsigned short b:2;
  unsigned short c:2;
#endif
};

The bit field must be 8 or less, and the byte break must be crossed

c

2022-09-30 21:16

2 Answers

It is not recommended that the C-language bit field be used for data representations that are intended for network transmission and reception (external input/output, such as or file reading).

See EXP11-C.Bitfield Structure Layout Not Assumptions in JPCERT.

The internal representation of a bit field structure has various processing system-dependent properties (e.g., internal padding), and the bit field structure has the following processing system-dependent constraints:

  • Alignment of bit fields on a per-storage basis. For example, bit fields can be assigned from the top or bottom of the per-storage basis.
  • Whether bit fields can cross per-storage boundaries.

Consequently, it is impossible to write a portable and secure code assuming a certain state regarding the layout of the members of the bit field structure.

Incidentally, this structure definition requires __BYTE_ORDER macro determination everywhere you access the variable a/a1+a2, which complicates unnecessary code.


2022-09-30 21:16

Bit fields are allowed to use _Bool, signed int, and unsigned int, all others are implementation dependent.It also depends on the implementation of how bits in the bit field are filled.
If you are aware of network byte orders, you may expect to compile on multiple platforms and compilers, but if so, implementation-dependent code is not recommended.

However, Visual C++ and GCC describe implementation-dependent behavior.I have checked the description of other compilers, and if you are satisfied with it, I think the code mentioned is fine.


2022-09-30 21:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.