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

前端 未结 3 786
轻奢々
轻奢々 2021-01-07 14:27

I am using Qt5 on Windows 7.
In my application (TCP server), I am currently using some methods from QTcpSocket class:
- QAbstractSocket::peerAddress(

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-07 15:05

    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.

提交回复
热议问题