Search code examples
qtsocketstcpmac-addresspeer

Qt/C++ : How to get remote PC (communication peer) MAC address?


I am using Qt5 on Windows 7.
In my application (TCP server), I am currently using some methods from QTcpSocket class:
- QAbstractSocket::peerAddress() in order to get the peer address;
- QAbstractSocket::peerPort() in order to get the peer port.

I would also want to get the MAC address of the communication peer.
Is this possible, without using a custom protocol (i.e. without having to exchange some custom messages between my app and the peer)? If yes, how?

Late Edit: There is now a very good solution - that I implemented few months ago. I tested it in the meantime and it works 100% flawlessly. Enjoy :)


Solution

  • Here is the code to get the MAC address of the communication peer.
    Under the hood, it uses the Windows command arp.
    Using Qt5.8, tested on Windows 7:

    QString getMacForIP(QString ipAddress)
    {
        QString MAC;
        QProcess process;
        //
        process.start(QString("arp -a %1").arg(ipAddress));
        if(process.waitForFinished())
        {
            QString result = process.readAll();
            QStringList list = result.split(QRegularExpression("\\s+"));
            if(list.contains(ipAddress))
                MAC = list.at(list.indexOf(ipAddress) + 1);
        }
        //
        return MAC;
    }
    

    Remark: remote peer must be on the same LAN.
    Another remark: you'll get an empty string for MAC if the IP address is not present.