我认为你有两个问题需要解决 . 首先,您需要确保在从字符缓冲区中提取整数数据后,它们在内存中正确对齐 . 接下来,您需要确保提取后整数数据的正确字节顺序 .
对齐问题可以通过__44819_来解决,该 union 包含叠加在正确大小的字符数组上的整数数据类型 . 可以使用标准 ntohs() 和 ntohl() 函数来解决网络字节顺序问题 . 这仅在发送软件也使用由这些函数的反转产生的标准字节顺序时才有效 .
以下是您可能会发现有用的一些UNTESTED函数 . 我认为他们应该做你想做的事情 .
#include
/**
* General routing to extract aligned integral types
* from the UDP packet.
*
* @param data Pointer into the UDP packet data
* @param type Integral type to extract
*
* @return data pointer advanced to next position after extracted integral.
*/
template
unsigned char const* extract(unsigned char const* data, Type& type)
{
// This union will ensure the integral data type is correctly aligned
union tx_t
{
unsigned char cdata[sizeof(Type)];
Type tdata;
} tx;
for(size_t i(0); i < sizeof(Type); ++i)
tx.cdata[i] = data[i];
type = tx.tdata;
return data + sizeof(Type);
}
/**
* If strings are null terminated in the buffer then this could be used to extract them.
*
* @param data Pointer into the UDP packet data
* @param s std::string type to extract
*
* @return data pointer advanced to next position after extracted std::string.
*/
unsigned char const* extract(unsigned char const* data, std::string& s)
{
s.assign((char const*)data, std::strlen((char const*)data));
return data + s.size();
}
/**
* Function to parse entire UDP packet
*
* @param data The entire UDP packet data
*/
void read_data(unsigned char const* const data)
{
uint16_t i1;
std::string s1;
uint32_t i2;
std::string s2;
unsigned char const* p = data;
p = extract(p, i1); // p contains next position to read
i1 = ntohs(i1);
p = extract(p, s1);
p = extract(p, i2);
i2 = ntohl(i2);
p = extract(p, s2);
}
希望有所帮助 .
EDIT:
我编辑了示例以包含字符串 . 它在很大程度上取决于字符串在流中的存储方式 . 此示例假定字符串是以null结尾的c字符串 .
EDIT2:
Whoopse,根据问题更改了代码以接受 unsigned 字符 .