C++中的netcat命令
netcat command in c++
我是 C++ 编码的新手。
我目前正在使用 qt 制作一个简单的 GUI,我想通过 TCP/IP.
向设备发送命令
当我将计算机连接到设备并通过终端发送命令时:
echo '3b00010000001b010001000000120000013000002713000300030101' | xxd -r -p | nc 192.168.1.101 30013
设备会做相应的事情。
我需要能够在 qt 中将此命令作为函数发送。谁能帮我?这是我目前所拥有的(不起作用)
Header:
#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[] = "\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
,因为它会在第一个空字符之前截断字符串。
我是 C++ 编码的新手。 我目前正在使用 qt 制作一个简单的 GUI,我想通过 TCP/IP.
向设备发送命令当我将计算机连接到设备并通过终端发送命令时:
echo '3b00010000001b010001000000120000013000002713000300030101' | xxd -r -p | nc 192.168.1.101 30013
设备会做相应的事情。
我需要能够在 qt 中将此命令作为函数发送。谁能帮我?这是我目前所拥有的(不起作用)
Header:
#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[] = "\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
,因为它会在第一个空字符之前截断字符串。