Click here to Skip to main content
15,867,568 members
Articles / General Programming / Internet
Tip/Trick

Testing Internet Connectivity

Rate me:
Please Sign up or sign in to vote.
4.87/5 (42 votes)
19 Jan 2011CPOL2 min read 128.5K   43   25
Some of the functions of our applications may require a run-time test of internet connectivity. Once internet connectivity is detected, the functions that require internet access may temporarily be disabled and/or the user can be notified via an alert message.

Introduction


Some of the functions of our applications may require a run-time test of internet connectivity. Once internet connectivity is detected, the functions that require internet access may temporarily be disabled and/or the user can be notified via an alert message. Otherwise, the application may result in error during operation or it may cause annoying problems for the user. In this article, I will try to demonstrate a couple of ways to overcome this problem.

Method 1: WebRequest


We may send a web request to a website which assumed to be online always, for example google.com. If we can get a response, then obviously the device that runs our application is connected to the internet.

C#
public static bool WebRequestTest()
    {
        string url = "http://www.google.com";
        try
        {
            System.Net.WebRequest myRequest = System.Net.WebRequest.Create(url);
            System.Net.WebResponse myResponse = myRequest.GetResponse();
        }
        catch (System.Net.WebException)
        {
            return false;
        }
        return true;
    }


Method 2: TCP Socket


There can be some delay in response of web request therefore this method may not be fast enough for some applications. A better way is to check whether port 80, default port for http traffic, of an always online website.



C#
public static bool TcpSocketTest()
    {
        try
        {
            System.Net.Sockets.TcpClient client =
                new System.Net.Sockets.TcpClient("www.google.com", 80);
            client.Close();
            return true;
        }
        catch (System.Exception ex)
        {
            return false;
        }
    }


Method 3: Ping


There can be some delay in response of web request, therefore this method may not be fast enough for some applications. A better way is to check whether port 80, default port for http traffic, of an always online website.

C#
public bool PingTest()
        {
            System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
 
            System.Net.NetworkInformation.PingReply pingStatus =
                ping.Send(IPAddress.Parse("208.69.34.231"),1000);
 
            if (pingStatus.Status == System.Net.NetworkInformation.IPStatus.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


You cannot use this method in .NET Compact Framework because there is no NetworkInformation namespace that comes with Compact Framework. However, you can use Smart Device Framework (http://www.opennetcf.com[^], Community Edition is free for download) provided by OpenNETCF. This framework comes with many other useful tools that .NET Compact Framework does not contain.



Notice that I used Google’s IP address 208.69.34.231. We could use Google’s web address www.google.com:



C#
System.Net.NetworkInformation.PingReply pingStatus = ping.Send("www.google.com",1000);


However, that will require DNS lookup which causes extra delay.



Method 4: DNS Lookup


Alternatively you can use DNS lookup to check internet connectivity. This method is faster than Ping method.

C#
public static bool DnsTest()
    {
        try
        {
            System.Net.IPHostEntry ipHe =
                System.Net.Dns.GetHostByName("www.google.com");
            return true;
        }
        catch
        {
            return false;
        }
    }


Method 5: Windows Internet API (WinINet)


WinINet API provides functions to test internet connectivity, such as InternetCheckConnection and InternetGetConnectedState. I do not have any idea about what these fucntions do exactly to test internet connectivity. You may refer to http://msdn.microsoft.com/en-us/library/aa384346(v=VS.85).aspx and http://msdn.microsoft.com/en-us/library/aa384702(v=VS.85).aspx for details.

An example usage can be:



C#
[DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int connDescription, int ReservedValue);

//check if a connection to the Internet can be established
    public static bool IsConnectionAvailable()
    {
        int Desc;
        return InternetGetConnectedState(out connDesc, 0);
    }



Summary


In this article, we have seen a couple of different ways to test internet connectivity. Each method has its own advantages and disadvantages. So, it is up to you to choose the best way for your platform and application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer
Turkey Turkey
Borned in Malatya, TURKEY. Graduated from Department of Computer Engineering, Eastern Mediterranean University, T.R.N.C

Currently, PhD student-Graduate Research Assistant in Computer Sciences Department at UW-Madison.

Comments and Discussions

 
PraiseThank you for your article. Pin
xamtra6-May-18 1:03
xamtra6-May-18 1:03 
PraiseThank you for your article. Pin
xamtra6-May-18 1:23
xamtra6-May-18 1:23 
QuestionI vote for the number 5 Pin
srfox2-Dec-17 18:13
professionalsrfox2-Dec-17 18:13 
GeneralMy vote of 5 Pin
JayantaChatterjee9-Aug-17 1:46
professionalJayantaChatterjee9-Aug-17 1:46 
QuestionIs there a way in C# to monitor a certain process DNS requests? Pin
era ahmadian11-May-15 3:32
era ahmadian11-May-15 3:32 
GeneralMy vote of 5 Pin
Gaurav Aroraa30-Oct-14 11:15
professionalGaurav Aroraa30-Oct-14 11:15 
GeneralMy vote of 5 Pin
Hamed_Farag18-Aug-13 8:03
Hamed_Farag18-Aug-13 8:03 
GeneralMy vote of 5 Pin
sandeshjkota15-May-13 1:35
sandeshjkota15-May-13 1:35 
I tried 1,2,3 and 4. And it works as expected. And also found another easy way:

private bool IsNetworkAvailable() {
return System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
}
GeneralMy vote of 4 Pin
Mykola Panas K.1-Feb-13 2:59
professionalMykola Panas K.1-Feb-13 2:59 
GeneralRe: But yes you have put down good options its worth of 5 , 5 fr... Pin
Shivprasad koirala13-Nov-11 0:44
Shivprasad koirala13-Nov-11 0:44 
GeneralRe: What if DNS server is down i agree to sledge method 5 is per... Pin
Shivprasad koirala13-Nov-11 0:41
Shivprasad koirala13-Nov-11 0:41 
GeneralRe: Also, you don't have to hardcode the google url. You could ... Pin
MrAnderson1st24-Jan-11 5:34
MrAnderson1st24-Jan-11 5:34 
GeneralReason for my vote of 5 Nice info Pin
cdolkan14-Mar-11 22:31
cdolkan14-Mar-11 22:31 
GeneralReason for my vote of 5 Good bunch Pin
thatraja5-Mar-11 4:30
professionalthatraja5-Mar-11 4:30 
GeneralReason for my vote of 5 Nice article. Good to know/learn tha... Pin
R&D Ninja14-Feb-11 21:48
R&D Ninja14-Feb-11 21:48 
GeneralReason for my vote of 4 I've always look for such article. Pin
Babak.Nia25-Jan-11 9:16
Babak.Nia25-Jan-11 9:16 
GeneralReason for my vote of 5 Nice article. Good to know/learn tha... Pin
Lokanta_b25-Jan-11 1:16
Lokanta_b25-Jan-11 1:16 
GeneralYou do not have to hard code the google url. You could have ... Pin
MrAnderson1st24-Jan-11 5:41
MrAnderson1st24-Jan-11 5:41 
GeneralIf google goes down on every server, that would be a first I... Pin
electrawinds21-Jan-11 2:12
electrawinds21-Jan-11 2:12 
GeneralReason for my vote of 4 good Pin
Pranay Rana18-Jan-11 23:11
professionalPranay Rana18-Jan-11 23:11 
GeneralReason for my vote of 5 good info! Pin
GPUToaster™18-Jan-11 20:14
GPUToaster™18-Jan-11 20:14 
GeneralReason for my vote of 5 Very Nice Pin
Khaniya18-Jan-11 18:29
professionalKhaniya18-Jan-11 18:29 
GeneralReason for my vote of 3 Methods 1,2,3 and 4 are complete cra... Pin
SledgeHammer0118-Jan-11 13:52
SledgeHammer0118-Jan-11 13:52 
GeneralRe: You are not completely right. Methods 1 & 2 depend on both D... Pin
Ozcan ILIKHAN19-Jan-11 5:22
Ozcan ILIKHAN19-Jan-11 5:22 
GeneralRe: You are not completely right. Methods 1 & 2 depend on both D... Pin
Member 125744733-May-17 1:18
Member 125744733-May-17 1:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.