【发布时间】:2019-02-24 19:13:16
【问题描述】:
我有一个 u_char* 动态数组,其中包含一些网络数据包的二进制数据。我想用一些整数值更改数据包中的目标端口号。假设包内的端口号偏移为ofs,长度为4字节。
我尝试了以下两种方法:
u_char* packet = new u_char[packet_size]; // Packet still empty
// Read packet from network ...
int new_port = 1234;
方法#1:
std::copy((u_char*)&new_port, (u_char*)&new_port+4, packet+ofs);
方法#2:
std::string new_port_str = std::to_string(new_port);
auto new_port_bytes = new_port_str.c_str();
std::copy(new_port_bytes, new_port_bytes+4, packet+ofs);
这两种方法都为端口号提供垃圾值(但数据包的其余部分都可以)。谁能帮帮我?
【问题讨论】:
-
考虑
memmove -
你为什么会期望这能工作?您是否有任何理由认为您的平台恰好在内存中以与网络碰巧将整数作为字节流通过线路发送的格式完全相同的格式在内存中表示整数?
-
你说垃圾是什么意思?你期待看到什么?
标签: c++ c c++11 networking packet