1 /*
2     SPDX-FileCopyrightText: 2016 Alex Spataru
3     SPDX-License-Identifier: MIT
4 */
5 
6 #pragma once
7 
8 #include <QObject>
9 
10 class QHostInfo;
11 class QUdpSocket;
12 class QHostAddress;
13 
14 /**
15  * \brief Implements a simple mDNS responder using Qt
16  *
17  * This implementation is able perform mDNS queries and mDNS responses in any
18  * operating system supported by the Qt network module.
19  *
20  * You can obtain the IP of an mDNS device using the \c lookup() function,
21  * the \c hostFound() signal will be emitted whenever this class interprets
22  * a mDNS response packet and obtains valid information about a remote host.
23  *
24  * You can change the name that the local computer uses to identify itself
25  * in the mDNS network using the \c setHostName() function.
26  *
27  * \todo Implement NSEC block code generation in the \c sendResponse() packet
28  */
29 class qMDNS : public QObject {
30     Q_OBJECT
31 
32   signals:
33     void hostFound (const QHostInfo& info);
34 
35   public:
36     static qMDNS* getInstance();
37 
38     QString hostName() const;
39     QString getAddress (const QString& string);
40 
41   protected:
42     explicit qMDNS();
43     ~qMDNS();
44 
45   public slots:
46     void setTTL (const quint32 ttl);
47     void lookup (const QString& name);
48     void setHostName (const QString& name);
49 
50   private slots:
51     void onReadyRead();
52     void readQuery (const QByteArray& data);
53     void sendPacket (const QByteArray& data);
54     void readResponse (const QByteArray& data);
55     void sendResponse (const quint16 query_id);
56 
57   private:
58     QString getHostNameFromResponse (const QByteArray& data);
59     QString getIPv4FromResponse (const QByteArray& data, const QString& host);
60     QStringList getIPv6FromResponse (const QByteArray& data, const QString& host);
61     QList<QHostAddress> getAddressesFromResponse (const QByteArray& data,
62                                                   const QString& host);
63 
64   private:
65     quint32 m_ttl;
66     QString m_hostName;
67     QString m_serviceName;
68     QUdpSocket* m_IPv4Socket;
69     QUdpSocket* m_IPv6Socket;
70 };
71