View Full Version : Detect network connection in QT

17th May 2014, 05:00
Hi every body,
I have a problem when i detect network connection in Windows has install VirtualBox and VMWare.
This is my code:

bool MainWindow::IsNetworkConnected()
bool bReturn = false;
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);
bool isUp = (bool)(flags && QNetworkInterface::IsUp);

// If this interface isn't running, we don't care about it
if ( !isRunning )
// We only want valid interfaces that aren't loopback/virtual and not point to point
if ( !ifaces[i].isValid() || isLoopback || isP2P || !isUp)
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() )

QString ip = addresses[a].toString();
if ( ip.isEmpty() )
bool foundMatch = false;
for (int j=0; j < possibleMatches.size(); j++)
if ( ip == possibleMatches[j] )
foundMatch = true;
if ( !foundMatch )
possibleMatches.push_back( ip );
qDebug() << "possible address: " << ifaces[i].humanReadableName() << "->" << ip;
return bReturn;

This function always return "true" when i disconnected internet conection.
And my Network and Share Center:

Please help me fix it.
Sorry my for my english skill.

17th May 2014, 09:07
Your code never sets bReturn to true so I cannot see a way that the function could return true.

17th May 2014, 11:56
Your code never sets bReturn to true so I cannot see a way that the function could return true.

Sorry. I want ask: "why foundMatch alway is true?". Please help me, i need some hint to check network is disconnect.

19th May 2014, 14:24
I don't see where possibleMatches is filled with any values. My guess would be foundMatch is actually always false because your for loop is from 0 to 0. Also, I don't know if it's what you intended, but there are no brackets around that for loop.