c++ - 解析通过 netcat 发送的字节
问题描述
我正在使用 C++ 中的套接字运行服务器。一旦我连接到客户端(为此使用 netcat),我就有一个函数可以读取客户端发送的内容并尝试解析它。
结构:
struct m
{
uint8_t m1;
}
struct str
{
uint64_t a;
uint32_t b;
uint32_t c;
}
功能:
int f(int x){
char s[1024];
if (read(x,s,sizeof(s)-1) > 0){
m *msg = reinterpret_cast<m *>(s);
if(msg->m1 == 0)
{
str *st = reinterpret_cast<str *>(s+1);
uint64_t a = htonll(st->u);
uint32_t b = htonl(st->v);
uint32_t c = htonl(st->w);
std::cout<<a<<" "<<b<<" "<<c<<std::endl;
}
else
{....
}
}
编辑:
uint64_t htonll(uint64_t value)
{
// The answer is 42
static const int num = 42;
// Check the endianness
if (*reinterpret_cast<const char*>(&num) == num)
{
const uint32_t high_part = htonl(static_cast<uint32_t>(value >> 32));
const uint32_t low_part = htonl(static_cast<uint32_t>(value & 0xFFFFFFFFLL));
return (static_cast<uint64_t>(low_part) << 32) | high_part;
} else
{
return value;
}
}
对于这种特殊情况,填充应该没有问题。我能够在*msghead == '0'
if 条件下正确解析和到达。但是,我没有从a, b and c
. 我已经尝试了很多案例,但是这些值没有多大意义。
我如何测试:
echo -n -e '\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01' | nc localhost 9000
理想情况下,我应该将输出设为 1 1 1,但我得到 0 0 0。此外,如果我将其更改为
echo -n -e '\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x01' | nc localhost 9000
我明白了1 0 0
我不确定我可以修复的字节顺序是否有问题,但无论哪种情况,似乎还有其他问题。
解决方案
这是问题所在:
uint64_t a = htons(st->u);
uint32_t b = htons(st->v);
uint32_t c = htons(st->w);
如果您阅读此 POSIX 参考资料,您将看到它htons
适用于16 位整数,并且htonl
适用于 32 位整数。64 位类型没有现有的标准函数。
但是,在使用 GNU C 库的 Linux 上bswap_x
,有一组函数具有 64 位变体。
推荐阅读
- c - 带有星号运算符的结构变量的括号
- org-mode - 组织模式捕获模板中的转义字符
- vue.js - 如何自动显示行之间的值差异(Vue.js 数据表)
- mysql - AWS 极光 MySQL
- javascript - 浏览器扩展程序可以读取网站的 cookie 吗?
- c++ - 在代码中将地图或火车站线表示为图形的最佳方法是什么?
- ios - 在 viewDidAppear 之前翻译 superview 时,UIHostingController 视图的转换不同步
- typescript - 抛出错误会导致“UnhandledPromiseRejectionWarning”
- python - 没有捕捉到 BeautifulSoup 所需的线条
- r - 在 R 中抓取 Zillow,并使用 Selector Gadget 查找纬度和经度