ping vs gethostbyname to check internet connection

I need to a way to check if pc is connected to the internet.
The most common option is to use ping, pinging google.com, but that is not a very good option so when searching for an alternative I came across gethostbyname.

using ping:
1
2
3
4
5
6
7
        if (system("ping -c1 www.google.com"))
        {
            qDebug() <<"There is no internet connection  \n";

        }
        else
            qDebug() << "-> connection established!\n";



using gethostbyname:
1
2
3
4
5
6
7
8
9
10
11
12
13
    char *hostname;
    struct hostent *hostinfo;

    hostname = "google.com";

    hostinfo = gethostbyname (hostname);

    if (hostinfo == NULL)
    {
        cout <<"There is no internet connection  \n";
    }
    else
       cout << "-> connection established!\n";


pinging google.com is not good because then you might have to verify that you are not a bot when using aftewards. I want to know if that will happen when using gethostbyname as well?
And also according to this answer https://www.linuxquestions.org/questions/programming-9/c-checking-internet-connection-248003/, gethostbyname might not be reliable:
It will grab that info from DNS cache if available, so it might not be the best test. You're better off finding a site that doesn't drop ICMP packets and do your own "ping" to it.


They were both pretty fast in my tests.
Last edited on
gethostbyname tells you nothing about whether a particular machine is up or down.
You're querying a DNS server, not the machine itself.

You're querying google DNS server won't it tell me if there is internet connecttion?
It'll tell you that your internet is alive, because you queried your DNS server.
With the disclaimer you added to the first post.

Seems I mis-read your post, I thought you wanted to make sure you could connect to a remote, not just establish local connectivity.

> pinging google.com is not good because then you might have to verify that you are not a bot when using aftewards.
This made no sense.
ping doesn't trigger captchas.


> The most common option is to use ping, pinging google.com, but that is not a very good option
Yeah, using system() to do anything is a bad idea.
- you've no control over what actual program gets run.
- the return result is useless if mickeysoft is your OS vendor.
Registered users can post here. Sign in or register to post.