Qt/C ++:如何获取远程PC(通信对等方)MAC地址? [英] Qt/C++ : How to get remote PC (communication peer) MAC address?
问题描述
我正在Windows 7上使用Qt5.
在我的应用程序( TCP服务器)中,我当前正在使用QTcpSocket类中的一些方法:
-QAbstractSocket::peerAddress()
以获取对等地址;
-QAbstractSocket::peerPort()
,以获取对等端口.
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.
我还想获取通信对等方的 MAC地址.
是否可以在不使用自定义协议的情况下(即无需在我的应用程序与对等方之间交换一些自定义消息)?如果是,怎么办?
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?
后期编辑:现在有 一个非常好的解决方案 -我几个月前实施的.我在此期间对其进行了测试,它可以100%完美地工作.享受:)
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 :)
推荐答案
以下是获取通信对等方的MAC地址的代码.
在后台,它使用Windows命令 arp .
使用在Windows 7上测试过的Qt5.8:
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;
}
备注:远程对等方必须位于同一LAN上.
另一点注意:如果IP地址不存在,您将获得一个用于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.
这篇关于Qt/C ++:如何获取远程PC(通信对等方)MAC地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!