如何将含0x00的uint8_t数组写入char*类型数据报?
处理包含0x00的uint8_t数组插入Datagram的问题
问题背景
现有代码可将不含0x00的uint8_t数组插入到Datagram的data段(char*类型),但当要插入的数组中包含0x00(十六进制空字节)时,担心复制操作会因0x00作为字符串终止符中断,导致数据不完整。
原可正常工作的代码:
// Datagram to represent the packet char datagram[4096], source_ip[32], *data, *pseudogram; // zero out the packet buffer memset(datagram, 0, 4096); // IP header struct iphdr *iph = (struct iphdr *)datagram; // UDP header struct udphdr *udph = (struct udphdr *)(datagram + sizeof(struct ip)); // Data part data = datagram + sizeof(struct iphdr) + sizeof(struct udphdr); uint8_t packet_bytes[] = { 0xff, 0xff, 0x81, 0x01, 0x01 }; memcpy(data, packet_bytes, 5);
现在需要插入的包含0x00的数组:
char packet_bytes[] = { 0xff, 0xff, 0x81, 0x00, 0x00, 0x00, 0x00, 0x30, 0x13, 0x43, 0x00, 0x01, 0x01, 0x01, 0x02, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x06, 0x00, 0x00, 0x10, 0x01, 0x01, 0x00, 0x63, 0x02, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x09, 0x04, 0x00, 0x0a, 0x00, 0x03, 0x01, 0x00, 0x11, 0x77, 0x25 };
解决方案
你的核心担忧是多余的——memcpy完全不受0x00影响,它按指定长度复制字节,不会因0x00停止。只需注意两个关键点:
使用正确的数组类型
将char packet_bytes[]改为uint8_t packet_bytes[],char可能是有符号类型(取决于编译器),无符号的uint8_t更适合表示网络数据包字节,避免符号扩展问题。传递正确的复制长度
不用手动数元素个数,直接用sizeof(packet_bytes)获取数组总字节数,数组修改后无需手动更新长度。
修正后的代码示例:
// Datagram to represent the packet char datagram[4096], source_ip[32], *data, *pseudogram; // zero out the packet buffer memset(datagram, 0, 4096); // IP header struct iphdr *iph = (struct iphdr *)datagram; // UDP header struct udphdr *udph = (struct udphdr *)(datagram + sizeof(struct ip)); // Data part data = datagram + sizeof(struct iphdr) + sizeof(struct udphdr); // 改用uint8_t定义字节数组 uint8_t packet_bytes[] = { 0xff, 0xff, 0x81, 0x00, 0x00, 0x00, 0x00, 0x30, 0x13, 0x43, 0x00, 0x01, 0x01, 0x01, 0x02, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x06, 0x00, 0x00, 0x10, 0x01, 0x01, 0x00, 0x63, 0x02, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x09, 0x04, 0x00, 0x0a, 0x00, 0x03, 0x01, 0x00, 0x11, 0x77, 0x25 }; // 用sizeof获取数组长度,自动处理所有字节(包括0x00) memcpy(data, packet_bytes, sizeof(packet_bytes));
关键注意事项
- 禁止使用
strcpy、strncpy等字符串操作函数,它们会把0x00当作终止符,导致复制提前停止。 - 确保
datagram剩余空间足够容纳packet_bytes,避免缓冲区溢出。
内容的提问来源于stack exchange,提问作者Ricardoke
相关产品推荐
相关产品推荐

