Getting MAC ID in Qt

highlander141 picture highlander141 · Mar 8, 2013 · Viewed 7.8k times · Source

I am using the following code to get the MAC ID in Qt.

main.cpp

#include <QtCore/QCoreApplication>
#include "QtNetwork/QNetworkInterface"
#include "QString"

QString getMacAddress()
{
    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces())
    {
        // Return only the first non-loopback MAC Address
        if (!(interface.flags() & QNetworkInterface::IsLoopBack))
            return interface.hardwareAddress();
        QString text = interface.hardwareAddress();
        qDebug() << text;
    }
    return QString();
}

int main(int argc, char *argv[])
{
    getMacAddress();
    QCoreApplication a(argc, argv);
    return a.exec();
}

I am getting nothing in Console? Guide me thanks...

Answer

user336063 picture user336063 · Mar 8, 2013

Try this code so show the hardware addresses of each interface:

QString getMacAddress()
{
    QString text;
    foreach(QNetworkInterface interface, QNetworkInterface::allInterfaces())
    {
        text += "Interface:"+interface.hardwareAddress()+"\n";
    }
    return text;
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    printf( "%s\n", getMacAddress().toAscii().constData() );
    exit(1);
    return a.exec();
}