C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 位字段和字节序大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经定义了以下结构来表示IPv4标头(直到选项字段):
struct IPv4Header
{
    // First row in diagram
    u_int32 Version:4;
    u_int32 InternetHeaderLength:4;     // Header length is expressed in units of 32 bits.
    u_int32 TypeOfservice:8;
    u_int32 TotALLENgth:16;

    // Second row in diagram
    u_int32 Identification:16;
    u_int32 Flags:3;
    u_int32 FragmentOffset:13;

    // Third row in diagram
    u_int32 TTL:8;
    u_int32 Protocol:8;
    u_int32 Headerchecksum:16;

    // Fourth row in diagram
    u_int32 sourceAddress:32;

    // Fifth row in diagram
    u_int32 DesTinationAddress:32;
};

我现在还使用Wireshark捕获了一个IP帧.作为数组文字,它看起来像这样

// Captured with Wireshark
const u_int8 cIPHeaderSample[] = {
    0x45,0x00,0x05,0x17,0xA7,0xE0,0x40,0x2E,0x06,0x1B,0xEA,0x51,0x58,0x25,0x02,0x0A,0x04,0x03,0xB9
};

我的问题是:如何使用数组数据创建IPv4Header对象?

由于不兼容的字节顺序,这不起作用:

IPv4Header header = *((IPv4Header*)cIPHeaderSamplE);

我知道像ntohs和ntohl这样的函数,但它无法弄清楚如何正确使用它们:

u_int8 version = ntohs(cIPHeaderSample[0]);
printf("version: %x \n",version);

// Output is:
// version: 0

有人可以帮忙吗?

解决方法

便携的方法是一次一个字段,对于长度超过一个字节的类型使用memcpy().您不必担心字节长度字段的字节顺序:
uint16_t temp_u16;
uint32_t temp_u32;
struct IPv4Header header;

header.Version = cIPHeaderSample[0] >> 4;

header.InternetHeaderLength = cIPHeaderSample[0] & 0x0f;

header.TypeOfServer = cIPHeaderSample[1];

memcpy(&temp_u16,&cIPHeaderSample[2],2);
header.TotALLENgth = ntohs(temp_u16);

memcpy(&temp_u16,&cIPHeaderSample[4],2);
header.Identification = ntohs(temp_u16);

header.Flags = cIPHeaderSample[6] >> 5;

memcpy(&temp_u16,&cIPHeaderSample[6],2);
header.FragmentOffset = ntohs(temp_u16) & 0x1fff;

header.TTL = cIPHeaderSample[8];

header.Protocol = cIPHeaderSample[9];

memcpy(&temp_u16,&cIPHeaderSample[10],2);
header.Headerchecksum = ntohs(temp_u16);

memcpy(&temp_u32,&cIPHeaderSample[12],4);
header.sourceAddress = ntohl(temp_u32);

memcpy(&temp_u32,&cIPHeaderSample[16],4);
header.DesTinationAddress = ntohl(temp_u32);

大佬总结

以上是大佬教程为你收集整理的c – 位字段和字节序全部内容,希望文章能够帮你解决c – 位字段和字节序所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。