File indexing completed on 2024-04-21 03:43:43

0001 /*
0002     SPDX-FileCopyrightText: 2016 Alex Spataru
0003     SPDX-License-Identifier: MIT
0004 */
0005 
0006 #pragma once
0007 
0008 #include <QObject>
0009 
0010 class QHostInfo;
0011 class QUdpSocket;
0012 class QHostAddress;
0013 
0014 /**
0015  * \brief Implements a simple mDNS responder using Qt
0016  *
0017  * This implementation is able perform mDNS queries and mDNS responses in any
0018  * operating system supported by the Qt network module.
0019  *
0020  * You can obtain the IP of an mDNS device using the \c lookup() function,
0021  * the \c hostFound() signal will be emitted whenever this class interprets
0022  * a mDNS response packet and obtains valid information about a remote host.
0023  *
0024  * You can change the name that the local computer uses to identify itself
0025  * in the mDNS network using the \c setHostName() function.
0026  *
0027  * \todo Implement NSEC block code generation in the \c sendResponse() packet
0028  */
0029 class qMDNS : public QObject {
0030     Q_OBJECT
0031 
0032   signals:
0033     void hostFound (const QHostInfo& info);
0034 
0035   public:
0036     static qMDNS* getInstance();
0037 
0038     QString hostName() const;
0039     QString getAddress (const QString& string);
0040 
0041   protected:
0042     explicit qMDNS();
0043     ~qMDNS();
0044 
0045   public slots:
0046     void setTTL (const quint32 ttl);
0047     void lookup (const QString& name);
0048     void setHostName (const QString& name);
0049 
0050   private slots:
0051     void onReadyRead();
0052     void readQuery (const QByteArray& data);
0053     void sendPacket (const QByteArray& data);
0054     void readResponse (const QByteArray& data);
0055     void sendResponse (const quint16 query_id);
0056 
0057   private:
0058     QString getHostNameFromResponse (const QByteArray& data);
0059     QString getIPv4FromResponse (const QByteArray& data, const QString& host);
0060     QStringList getIPv6FromResponse (const QByteArray& data, const QString& host);
0061     QList<QHostAddress> getAddressesFromResponse (const QByteArray& data,
0062                                                   const QString& host);
0063 
0064   private:
0065     quint32 m_ttl;
0066     QString m_hostName;
0067     QString m_serviceName;
0068     QUdpSocket* m_IPv4Socket;
0069     QUdpSocket* m_IPv6Socket;
0070 };