Извините, что оживил старый вопрос, но я сам обдумывал это и придумал решение:
QList<QString> possibleMatches;
QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
if ( !ifaces.isEmpty() )
{
for(int i=0; i < ifaces.size(); i++)
{
unsigned int flags = ifaces[i].flags();
bool isLoopback = (bool)(flags & QNetworkInterface::IsLoopBack);
bool isP2P = (bool)(flags & QNetworkInterface::IsPointToPoint);
bool isRunning = (bool)(flags & QNetworkInterface::IsRunning);
// If this interface isn't running, we don't care about it
if ( !isRunning ) continue;
// We only want valid interfaces that aren't loopback/virtual and not point to point
if ( !ifaces[i].isValid() || isLoopback || isP2P ) continue;
QList<QHostAddress> addresses = ifaces[i].allAddresses();
for(int a=0; a < addresses.size(); a++)
{
// Ignore local host
if ( addresses[a] == QHostAddress::LocalHost ) continue;
// Ignore non-ipv4 addresses
if ( !addresses[a].toIPv4Address() ) continue;
QString ip = addresses[a].toString();
if ( ip.isEmpty() ) continue;
bool foundMatch = false;
for (int j=0; j < possibleMatches.size(); j++) if ( ip == possibleMatches[j] ) { foundMatch = true; break; }
if ( !foundMatch ) { possibleMatches.push_back( ip ); qDebug() << "possible address: " << ifaces[i].humanReadableName() << "->" << ip; }
}
}
}
// Now you can peek through the entries in possibleMatches
// With VMWare installed, I get two entries, and the first one is the correct one.
// If you wanted to test which one has internet connectivity, try creating a tcp
// connection to a known internet service (e.g. google.com) and if the connection
// is successful, check the following on the tcp connection
/*
if ( socket->localAddress().toIPv4Address() )
{
for(int c=0; c < possibleMatches.size(); c++) if ( socket->localAddress().toString() == possibleMatches[c] ) { qDebug() << "Your LAN IP:" << possibleMatches[c]; }
}
*/
Возможно, вы захотите сделать его немного более устойчивым, чтобы код мог отслеживать как интерфейс, так и IP-адрес, но это может быть ненужным, поскольку я почти уверен, что интерфейс не может содержать более одного IP-адрес, и никакие два интерфейса не могут иметь одинаковый IP-адрес (поправьте меня, если я ошибаюсь в этом предположении).