Qt cannot connect to the server - qt

I am trying to create simple server that will just show when somebody have connected to me. Everything works fine when client and server use "localhost" as a host name to connect, but when I changed localhost to my ip address then I got timeout error :(
There is my code:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
server_status=0;
}
void MainWindow::on_starting_clicked()
{
tcpServer = new QTcpServer(this);
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newuser()));
if (!tcpServer->listen(QHostAddress::Any, 33333) && server_status==0) {
qDebug() << QObject::tr("Unable to start the server: %1.").arg(tcpServer->errorString());
ui->textinfo->append(tcpServer->errorString());
} else {
server_status=1;
qDebug() << tcpServer->isListening() << "TCPSocket listen on port";
ui->textinfo->append(QString::fromUtf8("Server started!"));
qDebug() << QString::fromUtf8("Server started!");
}
}
void MainWindow::on_stoping_clicked()
{
if(server_status==1){
foreach(int i,SClients.keys()){
QTextStream os(SClients[i]);
os.setAutoDetectUnicode(true);
os << QDateTime::currentDateTime().toString() << "\n";
SClients[i]->close();
SClients.remove(i);
}
tcpServer->close();
ui->textinfo->append(QString::fromUtf8("Server stopped!"));
qDebug() << QString::fromUtf8("Server stopped!");
server_status=0;
}
}
void MainWindow::newuser()
{
if(server_status==1){
qDebug() << QString::fromUtf8("New connection!");
ui->textinfo->append(QString::fromUtf8("New connection!"));
QTcpSocket* clientSocket=tcpServer->nextPendingConnection();
int idusersocs=clientSocket->socketDescriptor();
SClients[idusersocs]=clientSocket;
connect(SClients[idusersocs],SIGNAL(readyRead()),this, SLOT(slotReadClient()));
}
}
And for client:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
socket = new QTcpSocket(this);
socket->connectToHost("95.220.162.117", 33333);
socket->waitForConnected();
}
MainWindow::~MainWindow()
{
delete ui;
}
I am a novice in the field of working with network, so please explain me what I am doing wrong

"95.220.162.117" looks like a public European IP address. This public IP address is shared by all the computers/tablets/phones/etc. in your home/office. Think of it this way: The public IP address points to your router, not to a specific computer.
When a client sends a request to a public IP address, the router receives the request first. It is then the router's job to forward the request to the correct device... but in your case, your router doesn't know which device should receive the request!
There are two levels to making your connection work:
1. Private: Within your local network (Easier)
On your server, open your console and enter the following to find your private/local IP address:
ifconfig -a
Your local IP address is different from your public IP address. It identifies a specific computer on your local network. Make your client connect to this address, and your server should receive the request.
This only works when the client and the server are on the same local network (e.g. connected to the same router)
2. Public: Over the internet (Harder)
You need to set up Port Forwarding -- This tells your router to take requests received at port 33333 and forward them to your server.
To learn more about this topic, read up on Network Address Translation.

Related

Qt QUdpSocket triggers readyRead() on sending data

I have written following simple program for UDP communication:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::AnyIPv4, 4000);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readDataFromSocket()));
udpSocket->writeDatagram("Test Data", QHostAddress("192.168.2.91"), 3000);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::readDataFromSocket()
{
while (udpSocket->hasPendingDatagrams()) {
udpSocket->receiveDatagram();
qDebug()<<"UDP data received";
}
}
Now the problem is that, when I run this program, readyRead() also fires on sending data.
Few interesting findings:
I have tried sending data to different IPs on my network. For few IPs
it doesn't trigger my readyRead() function. But for most of the
IPs readyRead() does trigger.
Though udpSocket->hasPendingDatagrams() returns true, but it doesn't
have any data.
I am running Qt 5.12.3 (MSVC 2017, 32 bit). When I run same program in Qt 5.3.2 (MSVC 2010, 32 bit), it works fine, my readyRead() never fires.
Anyone can help?
As per qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddress &address, quint16 port) docs:
Warning: Calling this function on a connected UDP socket may result in an error and no packet being sent. If you are using a connected socket, use write() to send datagrams.

QT QTcpServer listen

i have a question about QT QTcpServer server->listen(QHostAddress, qint16). I have problems with the address.
I tried with QHostAddress("127.0.0.1"), and that worked. I tried with QHostAddress::Any, and that failed (error 10, not supported). I tried with QHostAddress::AnyIPv4, and that failed (same error). I tried with QHostAddress("0.0.0.0"), and that failed, with same error. I tried with the address of the interface, that worked.
NotificationServer::NotificationServer(QObject *parent) : QObject(parent) {
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
if (!server->listen(QHostAddress::Any, port)) {
qDebug() << "Server could not start." << server->serverError();
server = nullptr;
} else {
qDebug() << "Server started.";
}
}
It seems, that it is not possible making the QTcpServer listen on all interfaces. OS is Linux XUbuntu. How can i make the server listen at all interfaces?

libconnman-qt connect to wifi

Hi currently I am working on project that require to connect to wifi and I am using libconnman-qt.
Everything goes well (enable/disable wifi, list of wifi), until I found a problem to connect to the wifi. So when I connect the service to wifi by :
mCurrentNetworkService->setPassphrase(ui->linePassword->text());
mCurrentNetworkService->requestConnect();
Occurs an error that says : "Not Registered". I don't know what happen, since the lib not give any clue for me. Or maybe there is step that I missed?
You must first register an "agent" that can respond to requests for input from the connman daemon. Here is a simple example.
#include <networkservice.h>
#include <useragent.h>
class Wifi : public QObject {
Q_OBJECT
public:
Wifi(QObject *parent = 0) :
QObject(parent), m_agent(NULL), m_service(NULL) {
//Register an agent to handle requests from connmand
m_agent = new UserAgent(this);
//Connect to UserAgent signal
connect(m_agent, SIGNAL(userInputRequested(QString, QVariantMap)),
this, SLOT(agentRequestedUserInput(QString, QVariantMap)));
}
~Wifi() {}
public Q_SLOTS:
void agentRequestedUserInput(QString path, QVariantMap fields) {
Q_UNUSED(path)
QVariantMap reply;
reply.insert("Passphrase", QString("pass1234"));
m_agent->sendUserReply(reply);
}
void connectToService(QString servicePath) {
// Add logic to find NetworkService pointer for the service you will connect to
// pseudo code
// m_service = findService(servicePath);
m_service->requestConnect();
}
private:
UserAgent *m_agent;
NetworkService *m_service;
}

telnet client not connecting -- to QTCPserver

Why i am not able to connect to a server running on my localhost using telnet client ?
I am using windows-7 & telnet client is turned on in control panel.
Please suggest how to make it working ?
#define SERVER_PORT 5000
Tcp server is created in the tcpserver object :---
tcpserverobject::tcpserverobject(QObject *parent) :
QObject(parent), tcpServer(0)
{
tcpServer = new QTcpServer;
connect(tcpServer, SIGNAL(newConnection()), this, SLOT(on_newConnection()));
}
// Common slot for the tcpserver - thread
void tcpserverobject::dowork()
{
if (!tcpServer->listen(QHostAddress::LocalHost, SERVER_PORT )) {
qDebug() << "\n returning from server listning error .. !!! ";
return;
}
qDebug() << "\n server listning";
//while(1)
while(!m_bQuit)
{
}
}
Server new connection code :---
void tcpserverobject::on_newConnection()
{
QByteArray block;
block.append(" \n Hello from server .. !!!") ;
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
// Create new thread for this .. client request ..!!
qDebug() << "\n New connection request ..!!!";
qDebug() << "\n New client from:" << clientConnection->peerAddress().toString();
clientConnection->write(block);
clientConnection->flush();
clientConnection->disconnectFromHost();
qDebug() << "\n New connection request closed ..!!!";
}
Now i enter command in telnet :----
C:\Users\Admin> telnet
Welcome to Microsoft Telnet Client
Escape Character is 'CTRL+]'
Microsoft Telnet> open localhost 5000
Connecting To localhost...
I am able to make my server go in listen mode, as following statement is printed :--
qDebug() << "\n server listning";
But why telnet client is not able to connect to the server running on localhost & PORT = 5000 ?
In the function do work, you have this code: -
//while(1)
while(!m_bQuit)
{
}
This is going to stop the current thread from processing messages. If you want to be able to stop the server, have a slot, in the tcpserverobject class, which will close the connection to the QTcpServer when it receives a signal.

How a client app connect to an SSL server with a self-signed certificate in Qt?

I want to communicate with a POP3 server with ssl and port 995 with my client app
the certificate of server is self-signed and while running the app the error that received is:
The certificate is self-signed, and untrusted
A part of code is:
socket = new QSslSocket(this);
QFile certfile("D:\\hani\\cert\\localhost.localdomain.pem");
Q_ASSERT(certfile.open(QIODevice::ReadOnly));
QList<QSslCertificate> certList;
QSslCertificate cert(&certfile,QSsl::Pem);
certList.append(cert);
socket->addCaCertificate(cert);
socket->setCaCertificates(certList);
QList<QSslCertificate> serverCert = socket->caCertificates();
What can I do?
DO NOT, let me repeat, DO NOT call ignoreSslErrors(). It completely defeats the purpose of SSL/TLS. There are very special cases where it can be called safely, but this (self-signed certificate) is not a special case.
The following minimal code, ready to run, shows how to securely accept a server self-signed certificate. Do not shortcut it.
The driver:
int main(int argc, char** argv) {
QCoreApplication app(argc, argv);
QTextStream log(stdout);
DummyClient dummy(log);
QObject::connect(&dummy, SIGNAL(done()), &app, SLOT(quit()));
return app.exec();
}
The DummyClient class:
/*
* Show how to safely authenticate a TLS server which uses a self-signed certificate.
* Warning: No error handling to keep the code short.
*/
class DummyClient : public QObject {
Q_OBJECT
public:
DummyClient(QTextStream& log)
: _log(log),
_sock(new QSslSocket(this)) {
connect(_sock, SIGNAL(encrypted()), this, SLOT(onEncrypted()));
connect(_sock, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(onSslErrors(QList<QSslError>)));
connect(_sock, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(onErrors(QAbstractSocket::SocketError)));
// Trust store: which CAs or self-signed certs we are going to trust.
//
// We use setCaCertificates() instead than QSslSocket::addCaCertificates()
// because we don't want to trust the ~200 default CAs.
QList<QSslCertificate> trustedCas = QSslCertificate::fromPath("server-cert.pem");
if (trustedCas.empty()) {
qFatal("Error: no trusted Cas");
}
_sock->setCaCertificates(trustedCas);
bool mutualAuth = false;
if (mutualAuth) {
// Our identity
_sock->setPrivateKey("client-key.pem");
_sock->setLocalCertificate("client-cert.pem");
}
_log << "Connecting" << endl;
// Note: serverName must match the cert CN or alternative name.
Qstring serverName = "myserver.example.org";
_sock->connectToHostEncrypted(serverName, 995);
}
signals:
void done();
private slots:
void onEncrypted() {
_log << "onEncrypted" << endl;
/* Everything is good. Start communicating. */
emit done();
}
void onSslErrors(QList<QSslError> errors) {
QSslError first = errors.takeFirst();
_log << "onSslErrors: " << first.errorString() << endl;
/* Something went wrong in the TLS handshake. Inform the user and quit! */
emit done();
}
void onErrors(QAbstractSocket::SocketError) {
_log << "onErrors: " << _sock->errorString() << endl;
emit done();
}
private:
QTextStream& _log;
QSslSocket* _sock;
};
http://qt-project.org/doc/qt-5.1/qtnetwork/qsslsocket.html
Look at the description of QSslSocket::sslErrors:
If you want to continue connecting despite the errors that have occurred,
you must call QSslSocket::ignoreSslErrors() from inside a slot connected
to this signal.
DISCLAIMER: This is very ill-advised, as it leaves the server "wide open" to man-in-the-middle attacks

Resources