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

天大地大妈咪最大 提交于 2019-12-03 23:07:25

问题


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 :)


回答1:


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?

In general, no, this is not possible, since the communication peer may not even have a MAC address (e.g. if it is using networking hardware that isn't based on Ethernet). In particular, information about MAC addresses is not communicated by the IP, TCP, or UDP layers --- those layers use IP addresses instead. So if you want to find out the peer's MAC address you will need to do that at the application level, by having a program on the peer send it to you.

(One minor exception to the above: If you are communicating via IPv6 and using self-assigned link-local IPv6 addresses (e.g. fe80::blah), it is possible to derive a computer's MAC address from its self-assigned IPv6 address, because the self-assigned IPv6 address is typically derived from the MAC address and contains the MAC address as a subset of its IPv6 address. [Note this won't work across the Internet since link-local addresses are only useful when both machines are located on the same LAN])




回答2:


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.



来源:https://stackoverflow.com/questions/35247617/qt-c-how-to-get-remote-pc-communication-peer-mac-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!