分配给struct字段时,Unsigned short更改值

时间:2016-03-29 12:23:52

标签: c struct short

我有一个函数来解析20个字节长的IP头缓冲区:

void parseIp(struct ipHeader *ip, const void *buffer)
{
    uint8_t* b = buffer;
   // memcpy(b,buffer,20);
    ip->version = (b[0] & 0xf0) >> 4;
    ip->ihl = (b[0] & 0x0f);
    ip->dscp = (b[1] & 0xfC)>>2;
    ip->ecn = (b[1] & 0x3);

    unsigned short l = (b[2] << 8) | b[3];

    printf("%d\n",l);
    ip->length = l;
    ip->identification = (b[4] << 0xFF) | b[5];
}

struct ipHeader:

struct ipHeader {
    int version;
    int ihl;
    int dscp;
    int ecn;
    unsigned short length;
    unsigned short identification;
    int flags;
    int fragment_offset;
    int time_to_live;
    int protocol;
    unsigned short header_checksum;
    unsigned char source_ip[4];
    unsigned char destination_ip[4];
};

现在代码将l打印为467,这是正确的,但是当这个l被分配给struct字段长度时它会变为54017.我根本不明白发生了什么。我添加了变量l以确保不会发生溢出或类型转换错误,但它仍然会发生变化。

这是学校工作的一部分,所以我无法改变结构。

EDIT 完整代码:

#include <stdio.h>
#include <arpa/inet.h>
#include "ipheader.h"


/* Parses the given buffer into an IP header structure.
 * 
 * Parameters:
 * ip: pointer to the IP header structure that will be filled based
 *      on the data in the buffer
 * buffer: buffer of 20 bytes that contain the IP header. */
    void parseIp(struct ipHeader *ip, const void *buffer)
    {
        uint8_t* b = buffer;
       // memcpy(b,buffer,20);
        ip->version = (b[0] & 0xf0) >> 4;
        ip->ihl = (b[0] & 0x0f);
        ip->dscp = (b[1] & 0xfC)>>2;
        ip->ecn = (b[1] & 0x3);

        unsigned short l = (b[2] << 8) | b[3];

        printf("%d\n",l);
        ip->length = l;
        ip->identification = (b[4] << 8) | b[5];
    }


/* Builds a 20-byte byte stream based on the given IP header structure
 * 
 * Parameters:
 * buffer: pointer to the 20-byte buffer to which the header is constructed
 * ip: IP header structure that will be packed to the buffer */
void sendIp(void *buffer, const struct ipHeader *ip)
{
}


/* Prints the given IP header structure */
void printIp(const struct ipHeader *ip)
{
    /* Note: ntohs below is for converting numbers from network byte order
     to host byte order. You can ignore them for now
     To be discussed further in Network Programming course... */
    printf("version: %d   ihl: %d   dscp: %d   ecn: %d\n",
            ip->version, ip->ihl, ip->dscp, ip->ecn);
    printf("length: %d   id: %d   flags: %d   offset: %d\n",
            ntohs(ip->length), ntohs(ip->identification), ip->flags, ip->fragment_offset);
    printf("time to live: %d   protocol: %d   checksum: 0x%04x\n",
            ip->time_to_live, ip->protocol, ntohs(ip->header_checksum));
    printf("source ip: %d.%d.%d.%d\n", ip->source_ip[0], ip->source_ip[1],
            ip->source_ip[2], ip->source_ip[3]);
    printf("destination ip: %d.%d.%d.%d\n", ip->destination_ip[0],
            ip->destination_ip[1],
            ip->destination_ip[2], ip->destination_ip[3]);    
}

/* Shows hexdump of given data buffer */
void hexdump(const void *buffer, unsigned int length)
{
    const unsigned char *cbuf = buffer;
    unsigned int i;
    for (i = 0; i < length; ) {
        printf("%02x ", cbuf[i]);
        i++;
        if (!(i % 8))
            printf("\n");
    }
}

struct ipHeader {
    int version;
    int ihl;
    int dscp;
    int ecn;
    unsigned short length;
    unsigned short identification;
    int flags;
    int fragment_offset;
    int time_to_live;
    int protocol;
    unsigned short header_checksum;
    unsigned char source_ip[4];
    unsigned char destination_ip[4];
};

void parseIp(struct ipHeader *ip, const void *buffer);
void sendIp(void *buffer, const struct ipHeader *ip);

void printIp(const struct ipHeader *ip);
void hexdump(const void *buffer, unsigned int length);


#include <arpa/inet.h>
#include "ipheader.h"

int main()
{
    /* Feel free to modify this function to test different things */

    unsigned char bytes[] = {
        0x45, 0x00, 0x01, 0xd3, 0xda, 0x8d, 0x40, 0x00,
        0x40, 0x06, 0x8c, 0xd5, 0xc0, 0xa8, 0x01, 0x46,
        0x6c, 0xa0, 0xa3, 0x33 };

    struct ipHeader ip;

    parseIp(&ip, bytes);
    printIp(&ip);

    struct ipHeader ipfields = {
        4, // version
        28, // ihl
        4, // dscp
        0, // ecn
        htons(1500), // length
        htons(1234), // id
        1, // flags
        1024, // offset
        15, // time_to_live
        33, // protocol
        htons(0x1234), // checksum (invalid)
        {1, 2, 3, 4}, // source IP
        {5, 6, 7, 8} // destination IP
    };
    unsigned char sendbuf[20];

    sendIp(sendbuf, &ipfields);
    hexdump(sendbuf, sizeof(sendbuf));
}

3 个答案:

答案 0 :(得分:1)

对于给定的输入:

unsigned char bytes[] = { 0x45, 0x00, 0x01, 0xd3, 0xda, 
然后是代码:

unsigned short l = (b[2] << 8) | b[3];

生成l,其值为467

你在问题​​中说,&#34;因为这个l被分配给结构字段长度,所以它变为54017。&#34;。但事实并非如此。如果您在现有ip->length = l;之后立即添加一行:

printf("%d\n", ip->length);

您仍会看到467

我猜你提到的问题是你的printIp函数打印54017。这是因为该函数不会打印ip->length。它打印ntohs(ip->length)ntohs宏将值从567更改为54017

要解决此问题,请更改printIp功能以打印ip->length,而不是ntohs(ip->length)

从该功能中删除其他ntohs来电,并从htons的定义中删除ipfields。整数应该存储在struct ipHeader内的 h ost顺序(即本机顺序)中,并存储在 n etwork order(即big-endian)中在unsigned char缓冲区时。

可移植性注1:从技术上讲,您应该在这两个%hu语句中使用printf作为格式说明符,因为参数类型为unsigned short

可移植性注2: l == 467无论int大小,都与目前为止的一些评论/答案中的建议相反。但是,要在具有16位b[2]的系统上运行时支持0x7F大于int的值,您应该编写((unsigned)b[2] << 8) | b[3]

可移植性注3:最好使用uint16_t代替unsigned short,因为现在系统有32位unsigned short。如果这样做,printf格式说明符为"%"PRI16u,您可能需要#include <inttypes.h>

答案 1 :(得分:-1)

不确定您是否知道Endianness(Big endian / Little endian) 请参阅:https://en.wikipedia.org/wiki/Endianness

基本上,Little-endian格式反转顺序并将最低有效字节存储在较低的存储器地址,最高有效字节存储在最高存储器地址。

因此,当您指定I(467 = 0x1d3)时,它会以小端格式存储,具体取决于您的机器字节顺序(0xd301 = 54017)。

如果要分配正确的值,请使用htons。

答案 2 :(得分:-2)

正如其他人所提到的那样,看起来你可能会遇到一些转移问题,因为你的数据类型超出了宽度,导致......? (我不知道,似乎有关于这是否是定义的行为的争论)。在我的机器上,你的代码导致467这是正确的,幸运的是。然而,显式地定义引用定义了你想要的东西。

 unsigned short l = (((unsigned short)b[2]) << 8) | ((unsigned short)b[3]);

此外,你需要担心endianess(你是),因为网络头代码应该总是大端,我个人不会担心如果我没有必要的位移。对于多字节和字节边界的标题部分,我会做这样的事情:

 ip->length = ntohs(((unsigned short*)b)[1]);
 ip->identification = ntohs(((unsigned short*)b)[2]);
 ip->header_checksum = ntohs(((unsigned short*)b[5]);
 /*
 unsigned int sourceIpAddr = ntohl(((unsigned int*)b)[3]);
 unsigned int destIpAddr = ntohl(((unsigned int*)b[4]);
 Not sure what endianess you want for the source and destination IPs since those are just byte arrays
 */

注意,当您将b强制转换为其他指针类型时,索引会发生变化。

如果我完全控制结构,我会使用位字段创建整个事物,那么你根本不必担心转移,但你说结构是为你定义的。