【问题标题】:Passing data to the struct from iphdr从 iphdr 将数据传递给结构
【发布时间】:2017-11-17 14:30:27
【问题描述】:

我对 C 编程不是很有经验,但我尝试使用 C 捕获和分析数据包数据,但我有一个问题,我无法将数据传递给 stuct 内的变量。有我的结构:

struct ipOut {
    unsigned int ipVer;
    unsigned int headerDWORDS;
    unsigned int headerBytes;
    unsigned int typeOfService;
    unsigned int ipLength;
    unsigned int ident;
    unsigned int ttl;
    unsigned int protocolNum;
    unsigned int checkSum;
   };
struct ipAddr{
    char srcIP[16];
    char destIP[16];
};
struct hexOut{
    unsigned char * hexBuff;
};
struct sockaddr_in src, dest;

我从套接字获得了工作数据并将缓冲区发送到 iphdr:

void ipHeaderOutput(unsigned char * buff, int data) {
    packetNum++;
    struct iphdr *iph = (struct iphdr*)buff;
    memset(&src, 0, sizeof(src));
    memset(&dest, 0, sizeof(dest));
    src.sin_addr.s_addr = iph->saddr;
    dest.sin_addr.s_addr = iph->daddr;

    struct ipOut ipHeader[packetNum];
    ipHeader[packetNum].ipVer = iph->version;
    ipHeader[packetNum].headerDWORDS = (unsigned int)iph->ihl;
    ipHeader[packetNum].headerBytes = (unsigned int)iph->ihl*4;
    ipHeader[packetNum].typeOfService = (unsigned int)iph->tos;
    ipHeader[packetNum].ipLength = ntohs(iph->tot_len);
    ipHeader[packetNum].ident =  ntohs(iph->id);
    ipHeader[packetNum].ttl = (unsigned int)iph->ttl;
    ipHeader[packetNum].protocolNum = (unsigned int)iph->protocol;
    ipHeader[packetNum].checkSum = ntohs(iph->check);

    struct ipAddr ipAddr[packetNum];
    strcpy(ipAddr[packetNum].srcIP, inet_ntoa(src.sin_addr));
    strcpy(ipAddr[packetNum].destIP, inet_ntoa(dest.sin_addr));
}

ipAddr 结构完美地获取数据,没有任何问题。但是,数据根本没有传递到 ipOut 结构。我在将数据从缓冲区传递到 hexOut 结构时也遇到了同样的问题:

void hexDataOut(unsigned char * buff, int data){
    hexNum++;

    struct hexOut h[hexNum];
    h[hexNum].hexBuff = (unsigned char *)malloc(65536);
    memcpy(h[hexNum].hexBuff, buff, 65536);
    h[hexNum].hexBuff = buff;
}

这也是创建动态结构标签的正确方法吗?

【问题讨论】:

    标签: c arrays linux sockets struct


    【解决方案1】:

    让我们仔细看看这两行:

    struct ipOut ipHeader[packetNum];
    ipHeader[packetNum].ipVer = iph->version;
    

    第一个定义了一个local变量ipHeader,它是一个packetNum元素的数组。

    第二行使用越界索引packetNum访问数组中的元素。

    首先,为什么将ipHeader声明为数组?其次,为什么将它定义为 local 变量?第三,越界会导致未定义的行为,这会使你的整个程序格式错误并且无效。

    稍后与 ipAddr 变量相同。

    【讨论】:

    • 1.我将它定义为数组,因为我想为每个数据包创建一个新变量(例如 ipHeader1、ipHeader2 等)。 2. 是的,我是白痴,我应该更正它 3. 我会阅读有关未定义行为的信息,谢谢
    • @MatthewDarens 如果您希望数组在调用之间存在,那么它们不能被定义为局部变量。相反,要么使用全局变量,要么将它们作为指针传递给函数。如果您不希望数组在编译时设置为固定大小,则必须研究动态allocationreallocation。最后,请记住,数组索引是基于 0 的,因此 N 元素数组的索引从 0N - 1(含)。
    • 谢谢,我会努力解决的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多