C ++中的netcat命令

时间:2018-11-06 11:35:11

标签: c++ qt netcat

在C ++编码方面,我是个新手。 我目前正在使用qt制作简单的GUI,我想在其中通过TCP / IP向设备发送命令。

当我将计算机连接到设备并通过终端发送命令时:

echo '3b00010000001b010001000000120000013000002713000300030101' | xxd -r -p | nc 192.168.1.101 30013

设备会相应地执行操作。

我需要能够在qt中将此命令作为功能发送。谁能帮我?这就是我到目前为止(不起作用)

标题:

#ifndef SOCKET_H
#define SOCKET_H

#include <QObject>
#include <QTcpSocket>
#include <QtDebug>
#include <string>

using namespace std;

class Socket : public QObject
{
    Q_OBJECT
public:
    explicit Socket(QObject *parent = nullptr);

    void Connect(const QString &host, const string &cmd);

private:
    QTcpSocket *socket;
};

#endif // SOCKET_H

Cpp:

#include "socket.h"

Socket::Socket(QObject *parent) : QObject(parent)
{

}

void Socket::Connect(const QString &host, const string &cmd)
{
    //connect
    socket = new QTcpSocket(this);
    socket->connectToHost(host,30013);

    if(socket->waitForConnected(1500))
    {
        qDebug() << "Connected";

        //send
        socket->write(cmd.c_str(), cmd.size());
        socket->waitForBytesWritten(1000);

        //close
        socket->close();
    }

    else
        qDebug() << "Not Connected";

}

然后我要通过以下方式发送命令:

Socket.Test
Test.Connect("192.168.1.101","3b00010000001b010001000000120000013000002713000300030101")

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

由于您的命令是固定字符串,因此您可以直接直接输入字符:

const char data[] = "\x3b\x00\x01\x00\x00\x00\x1b\x01\x00\x01\x00\x00\x00\x12\x00\x00\x01\x30\x00\x00\x27\x13\x00\x03\x00\x03\x01\x01";
Test.Connect("192.168.1.101",string(data, sizeof(data)-1));

请注意,由于数据中嵌入了空字符,因此不能简单地将字符串文字传递给std::string,因为它将截断第一个空字符之前的字符串。