1

My application connects to a tcp server. I'd like it to be aware of being running on the same host as the server app, so it can eventually directly lauch the server process if it's not up.

As the server listens on an interface and the application resolves a hostname to connect to the server, it's not so obvious for me to determine if the configured hostname used to connect the server points to the same host as the server or not.

I'd like something like this:

bool isThisLocalHost(QString hostName) {
     //resolve hostname's address
     //list localhost interfaces ip or hw addresses ?
     //if the hostname address matches one of the host interfaces address
     //pseudo code         
     bool bRes = interfaces_addresses_list.contains(hostname_address);

     return bRes;
}

I'm actually trying to achieve this with QNetworkInterface, QNetworkAddressEntry, QHostInfo, QHostAddress.

Maybe is there a simple way?

spacm
  • 190
  • 3
  • 18
  • It's not sufficient to check if it's a localhost (127.x.x.x), you must also check if it's the address of any of the local interfaces. – Kuba hasn't forgotten Monica May 10 '16 at 19:36
  • Yes, i think my answer does the same as yours, but in a blocking way (what i don't mind in my usecase). Didn't see the "How to check if network address is local in Qt" question. – spacm May 11 '16 at 07:33

2 Answers2

1

Here is what i got:

bool isThisLocalHost(QString hostName) {
    QList <QHostAddress> lAddrHostName = QHostInfo::fromName(hostName).addresses();
    QList <QHostAddress> lAddrLocalHostInterfaces = QNetworkInterface::allAddresses();
    bool bRes = false;
    foreach (QHostAddress addr, lAddrHostName) {
        bRes = bRes || lAddrLocalHostInterfaces.contains(addr);
    }
return bRes;
}
spacm
  • 190
  • 3
  • 18
0

QHostAddress has isLoopback() which should get you what you need.

If you just want to know if you're connected to yourself this is (partly?) a duplicate of this question.

Community
  • 1
  • 1
Joe
  • 7,378
  • 4
  • 37
  • 54