Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Extracting Local Network Configuration via Qt5

Tech 1

Accessing local network configuration parameters such as the host identifier, IP addresses, and MAC addresses is a fundamental requirement in many desktop applications. The Qt Network module provides a dedicated set of classes—QHostInfo, QNetworkInterface, and QNetworkAddressEntry—to accomplish this efficiently.

To begin, the project configuration must explicitly link against the network module. The following .pro configuration establishes the necessary dependencies:

QT += core gui network
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = NetworkInspector
TEMPLATE = app
CONFIG += c++14

SOURCES += \
    main.cpp \
    networkpanel.cpp

HEADERS += \
    networkpanel.h

The application entry point initializes the Qt event loop and instantiates the primary interface:

#include "networkpanel.h"
#include <QApplication>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    NetworkPanel inspector;
    inspector.resize(400, 200);
    inspector.show();
    return app.exec();
}

The header file declares the interface components and the slots responsible for data retrieval. It inherits from QWidget and organizes the layout elements privately.

#ifndef NETWORKPANEL_H
#define NETWORKPANEL_H

#include <QWidget>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QGridLayout>
#include <QMessageBox>
#include <QtNetwork/QHostInfo>
#include <QtNetwork/QNetworkInterface>

class NetworkPanel : public QWidget {
    Q_OBJECT

public:
    explicit NetworkPanel(QWidget *parent = nullptr);
    ~NetworkPanel();

private:
    QLabel *lblHost;
    QLabel *lblPrimaryIp;
    QLineEdit *edtHost;
    QLineEdit *edtPrimaryIp;
    QPushButton *btnShowAll;
    QGridLayout *layout;

    void fetchLocalHostData();

private slots:
    void onShowDetailsClicked();
};

#endif // NETWORKPANEL_H

The implementation file constructs the UI grid, populates the initial fields using QHostInfo, and triggers a detailed enumeration of all available adapters when reuqested. The logic incorporates safe index validation and filters for active network states.

#include "networkpanel.h"

NetworkPanel::NetworkPanel(QWidget *parent)
    : QWidget(parent)
{
    lblHost = new QLabel(tr("System Identifier:"));
    edtHost = new QLineEdit;
    edtHost->setReadOnly(true);

    lblPrimaryIp = new QLabel(tr("Primary Address:"));
    edtPrimaryIp = new QLineEdit;
    edtPrimaryIp->setReadOnly(true);

    btnShowAll = new QPushButton(tr("Enumerate Adapters"));

    layout = new QGridLayout(this);
    layout->addWidget(lblHost, 0, 0);
    layout->addWidget(edtHost, 0, 1);
    layout->addWidget(lblPrimaryIp, 1, 0);
    layout->addWidget(edtPrimaryIp, 1, 1);
    layout->addWidget(btnShowAll, 2, 0, 1, 2);

    fetchLocalHostData();

    connect(btnShowAll, &QPushButton::clicked, this, &NetworkPanel::onShowDetailsClicked);
}

void NetworkPanel::fetchLocalHostData() {
    const QString hostName = QHostInfo::localHostName();
    edtHost->setText(hostName);

    QHostInfo resolution = QHostInfo::fromName(hostName);
    QList<QHostAddress> addresses = resolution.addresses();

    if (!addresses.isEmpty()) {
        for (const QHostAddress &addr : addresses) {
            if (addr.protocol() != QAbstractSocket::UnknownNetworkLayerProtocol) {
                edtPrimaryIp->setText(addr.toString());
                break;
            }
        }
    }
}

void NetworkPanel::onShowDetailsClicked() {
    QString report;
    const QList<QNetworkInterface> adapters = QNetworkInterface::allInterfaces();

    for (const QNetworkInterface &adapter : adapters) {
        if (!adapter.flags().testFlag(QNetworkInterface::IsUp) ||
            !adapter.flags().testFlag(QNetworkInterface::IsRunning)) {
            continue;
        }

        report.append(tr("Adapter: %1\n").arg(adapter.name()));
        report.append(tr("MAC: %2\n\n").arg(adapter.hardwareAddress()));

        const QList<QNetworkAddressEntry> entries = adapter.addressEntries();
        for (const QNetworkAddressEntry &entry : entries) {
            report.append(tr("\tIP: %1\n").arg(entry.ip().toString()));
            report.append(tr("\tNetmask: %2\n").arg(entry.netmask().toString()));
            report.append(tr("\tBroadcast: %3\n\n").arg(entry.broadcast().toString()));
        }
    }

    QMessageBox::information(this, tr("Network Configuration"), report);
}

NetworkPanel::~NetworkPanel() {}

Upon execution, the primary window immediately resolves the system hostname and populates the corresponding fields. Activating the enumeration button iterates through every active network adapter, extracting hardware addresses and associated IP configurations, then presents the compiled data in a modal dialog. This approach ensures compatibility with both IPv4 and IPv6 environments while maintaining a clean separation between UI construction and network querying logic.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.