QT TCP 客户端发送数据,但 netcat 接收随机值

问题描述 投票:0回答:1

我面临着一个在 QT 中实现的简单 TCP 客户端的愚蠢且令人沮丧的问题。 具体来说,它是一个控制台应用程序,其中实例化套接字,然后连接到侦听环回的服务器 (netcat)。它发送的内容与 netcat 接收的内容不对应。 此外,结果是不确定的(即每次数据都不同) 代码片段如下

#include <QCoreApplication>
#include <QDebug>
#include <QByteArray>
#include <QTcpSocket>

enum class Command: unsigned char {
    getNodeConnectionStatus = 0x00,
    getNodeHopCount,
    getNodesParent = 0x10
};

struct CommandHeader {
    Command command;
    size_t size;
} __attribute__((packed,aligned(1)));

struct Address {
    unsigned char value[24];
} __attribute__((packed,aligned(1)));

struct CommandPayload {
    struct Address address;
};

struct NodeHopCount: public CommandPayload
{
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QTcpSocket socket;
    socket.connectToHost("localhost", 2500);

    CommandPacket p;
    p.header.command = Command::getNodeHopCount;
    p.header.size = 1;

    struct NodeHopCount payload;
    
    memset(payload.address.value, '\0', 24);
    memcpy(payload.address.value, "AA:BB:CC:DD:EE:FF:00:11", 23);

    p.payload = new unsigned char[sizeof(payload)];

    memset(p.payload, '\0', sizeof(payload));
    memcpy(reinterpret_cast<void *>(p.payload), reinterpret_cast<void *>(&payload), sizeof(payload));
    QByteArray bytes(reinterpret_cast<char *>(&p), sizeof(p.header) + sizeof(payload));

    socket.write(bytes);
    socket.flush();
    socket.close();
    return a.exec();
}

这是两次连续运行的输出

solux [bin]$ nc -l -p 2500 -x -vv
Listening on any address 2500 (rtsserv)
Connection from 127.0.0.1:36670
▒����l��]U Received 33 bytes from the socket
00000000  01 01 00 00  00 00 00 00  00 1A 81 86  C8 7F 00 00  ................
00000010  C0 6C ED 92  5D 55 00 00  01 00 00 00  00 00 00 00  .l..]U..........
00000020  20                                                                  
Total received bytes: 33
Total sent bytes: 0
solux [bin]$ nc -l -p 2500 -x -vv
Listening on any address 2500 (rtsserv)
Connection from 127.0.0.1:50468
▒a%�bp�U Received 33 bytes from the socket
00000000  01 01 00 00  00 00 00 00  00 1A 61 00  25 7F 00 00  ..........a.%...
00000010  C0 1C 62 70  AF 55 00 00  01 00 00 00  00 00 00 00  ..bp.U..........
00000020  20                                                                  
Total received bytes: 33
Total sent bytes: 0

这似乎是一个指针问题,但我无法找出根本原因。 有人可以帮助我吗?

更新 我忘记了一块 这是CommandPacker的定义,非常抱歉 谢谢伊戈尔·坦德尼克

struct CommandPacket {
    struct CommandHeader header;
    unsigned char *payload;
};

c++ qt tcp
1个回答
0
投票
QByteArray bytes(reinterpret_cast<char *>(&p), sizeof(p.header));
bytes.append(reinterpret_cast<char *>(&payload), sizeof(payload));

这两条数据不是一个块。您必须单独复制并获取它们!您也可以只执行 2 次写入,而不是将数据复制到单个 QByteArray。

最后,添加对 IO 函数返回值的检查!

© www.soinside.com 2019 - 2024. All rights reserved.