See if the internet is available in C#


There are many ways you can test your network to see if the internet is available. Some methods may indicate that the network is connected if your local network is available even though the internet is not. Even if you avoid that sort of problem, there’s always the chance that the network will go down (or come back up) right after you test it, so your program can never be completely sure that the internet is there. Even if the network really is there, the site you want to visit may be down.

Perhaps the best method for testing the internet is to simply attempt whatever task you need to perform and see if it works.

However, if your network connection is usually reasonably stable, it may be useful to know if it’s worth even trying to use the internet. The following IsInternetConnected method uses ping to see if it can reach the Google server in a reasonably efficient manner.

private bool IsInternetConnected(int timeout)
        Ping ping = new Ping();
        String host = "";
        PingReply reply = ping.Send(host, timeout);
        return (reply.Status == IPStatus.Success);
        return false;

The method sends a ping request to the host You can use some other server if you like. For example, if your program will be accessing a company server, you may as well use that so you can tell if that server is available.

The PingReply object’s Status property indicates whether the server responded to the ping request within the specified timeout period, which is in milliseconds.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in internet, interoperability and tagged , , , , , , , , , , , , . Bookmark the permalink.