【问题标题】:c - remove first 4 bytes of datac - 删除前 4 个字节的数据
【发布时间】:2012-12-28 23:12:06
【问题描述】:

我正在读取一个数据包,但我需要从数据包中删除前四个字节和最后一个字节以获得我需要的内容,您将如何在 C 中执行此操作?

/* Build an input buffer of the incoming message. */
    while ( (len=read(clntSocket, line, MAXBUF)) != 0)
    {
            msg = (char *)malloc(len + 1);
            memset(msg, 0, len+1);
            strncpy(msg, line, len);
        }
    }

传入的数据是 char 和 int 数据的混合。

【问题讨论】:

  • 前四个字节真的没有有价值的信息吗?

标签: c offset packet-capture


【解决方案1】:

您可以更改strncpy源的地址:

while ( (len=read(clntSocket, line, MAXBUF)) != 0)
{
        msg = (char *)calloc(len -3, 1); // calloc instead of malloc + memset
        strncpy(msg, line+4, len);
    }
}

PS:我假设那行是char*。

【讨论】:

    【解决方案2】:

    如果 line 是 char *,你可以简单地从 (line + 4) 开始复制,它看起来是。 并且复制比len少5个字节,这样会丢掉最后一个字节。

    即使其非常明确(假设您之前的 malloc,它在缓冲区的末尾留下了一些安全性)。

    char *pFourBytesIn = (line + 4);
    int adjustedLength = len - 5;
    strncpy(msg, pFourBytesIn, adjustedLength);
    msg[adjustedLength] = '\0';
    

    【讨论】:

      猜你喜欢
      • 2015-01-11
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      相关资源
      最近更新 更多