The solution I’m going to show you here only works if:
- The program
arp
is installed on the machine running your program.
- The format of the output
arp
is always the same (I believe it is).
Basically, you spin the arp
, captures the output produced by it, and finds the desired information. The code below has been tested on Windows because by the output you showed it looks like you are using Windows itself (fix me if I’m wrong). The function below takes the IP address as a string and returns the physical address of the machine that has that IP address. The code is well commented, I hope you can catch without much difficulty.
QString obterEnderecoFisico(const QString &enderecoIP)
{
// A classe QProcess representa um processo.
QProcess processoARP;
// Esecificar o nome do programa, que é arp.
processoARP.setProgram("arp");
// Especificar os argumentos.
// Estou usando os mesmos argumentos que foram mostrados na pergunta.
processoARP.setArguments(QStringList() << "-a" << enderecoIP);
// Rodar o programa.
processoARP.start();
// Esperar o processo concluir.
processoARP.waitForFinished();
// Ler toda a saída produzida pelo processo.
QString saida = processoARP.readAll();
// Separar a saída por linhas.
QStringList saidaEmLinhas = saida.split('\n');
// Obter a linha que contém a informação desejada.
QString linhaImportante = saidaEmLinhas.at(3);
// Cada campo da linha importante é separado por vários espaços.
// Precisamos obter cada campo dessa linha.
QStringList linhaImportanteEmPartes = linhaImportante.split(' ', QString::SkipEmptyParts);
// O endereço físico é o segundo campo.
QString enderecoFisico = linhaImportanteEmPartes.at(1);
// Retornar o endereço físico como uma string.
return enderecoFisico;
} // É isso.
Then you use it like this:
ui->label->setText(obterEnderecoFisico("192.168.0.1"));
To change the text displayed in label
to the physical address of the machine having the IP address 192.168.0.1.
The code you posted in the question determines the physical address of the network interfaces of the machine running your program (not the router).
Edit:
I forgot to mention that for this to work, you must specify the IP address of a machine that is on the local network, because otherwise the arp
will not find a machine with that IP address and the output will not be in the expected format. If you want to make this function more robust, you can watch the output of the arp
when the specified address is not found and adapt the code to handle it. As I don’t know the language you are using (I use Windows in English) I didn’t implement this part because I imagine that the output would be different.
I think Qt doesn’t have any facilitator for raw communication, it will probably have to do right into C++, and implement individually for each platform.
– Bacco
@Bacco is what I imagined, I will try here and if I can put as answer ;)
– Guilherme Nascimento