netcat command in c++

netcat command in c++

本文关键字:c++ in command netcat      更新时间:2023-10-16

当谈到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")

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

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

const char data[] = "x3bx00x01x00x00x00x1bx01x00x01x00x00x00x12x00x00x01x30x00x00x27x13x00x03x00x03x01x01";
Test.Connect("192.168.1.101",string(data, sizeof(data)-1));

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