But what about those with unsigned int
Basically, as noted, C does not guarantee the size of an unsigned int ; there were platforms on which int and unsigned int were 16-bit, such as PDP-11, and Motorola 68k processors with some compilers (other compilers made them 32-bit), and it could still be some 16-bit microprocessors.
So, if you send data by wire, it is better to use the types defined in <stdint.h> , if available.
In practice, the machines you use will almost certainly have a 32-bit unsigned int , although some Cray machines have a 64-bit int and even short ! But itβs better to use the types defined in <stdint.h> .
or those where a certain number of bits are indicated (for example, u_int16_t doff: 4;).
If the value is shorter than the byte, as it would be for a 4-bit field, the byte order does not matter.
However, note that the order of the bit fields in a sequence of 1, 2, or 4 bytes is also not specified by C, so you should not use bit fields in the data sent over the wire. (Yes, some UN * Xes use them in structures for IPv4 and TCP headers, but this only works if the compilers that the provider uses for architectures that support all the set bit fields in the same order, and if third-party compilers, such as GCC do the same.)
So the right way to handle the IPv4 header is to do something like
struct ip { uint8_t ip_vhl; #define IP_V(ip) (((ip)->ip_vhl & 0xf0) >> 4) #define IP_HL(ip) ((ip)->ip_vhl & 0x0f) uint8_t ip_tos; uint16_t ip_len; uint16_t ip_id; uint16_t ip_off; #define IP_DF 0x4000 #define IP_MF 0x2000 #define IP_OFFMASK 0x1fff uint8_t ip_ttl; uint8_t ip_p; uint16_t ip_sum; struct in_addr ip_src,ip_dst; };
use this structure to declare the ip_hdr pointer for the IP header and:
- to extract the version, use
IP_V(ip_hdr) ; - to retrieve the length of the header, use
IP_HL(ip_hdr) .
If your ip.h provider ip.h uses bit fields, do not use your provider ip.h header; use your own caption. In fact, even if the header of your ip.h provider ip.h not use bit fields, do not use the ip.h header of your provider; use your own caption. This is not the case if the definition of the IP header is OS dependent, because ....
(What tcpdump has done for several releases now, the above is taken from his ip.h )