大小端网络字节序图解
以下是直观展示大小端字节序的图,其中“高”、“低”表示内存地址;“先”、“后”表示在网络收发数据是读取数据的顺序,即从低地址开始读取。
linux 对网络字节序的统一处理
CPU get data D from skb, and use LOCAL DATA = D to save network data to local CPU date struct
in linux kernel :
#define ETH_P_IP 0x0800
the ethernet II MAC header
|------------------|-----------------|-----------------|---------------|
| 6 bytes Dest MAC | 6 bytes Src MAC | 2 bypes TYPE | data body ... |
|------------------|-----------------|-----------------|---------------|
IF the `data body` is IP data, then the `TYPE` will be 0x0800
On the big endian CPU we use a int32 variable to save the TYPE
everything is OK;
On little endian CPU, cus the 0x0800 is saved on the little
hardware network card just fetch data from data buffer byte by byte, we must ensure the data in the buffer are all in network
byte order ). we need map it to the bigendian space use cpu_to_be16(0x8000)
cpu_to_be16:
transe 16bit data from cpu endian mode(space) to big endian mode(space)
on little endian CPU swap the two byte
on big endian CPU do nothing
note: `LOCAL DATA` is in big endian space cus we just save it
from skb(net order) directly or already mapped to bigendian space
simply: always handle the network data in bigendian space
if data is from network use it direcly
else data defined on CPU, map it to big endian space
using cpu_to_beXX()
Contact: bigjordon@163.com