What is the best way to check for Internet connectivity using .NET?

后端 未结 27 2047
感动是毒
感动是毒 2020-11-22 07:41

What is the fastest and most efficient way to check for Internet connectivity in .NET?

相关标签:
27条回答
  • 2020-11-22 08:28

    You can use NetworkInterface.GetIsNetworkAvailable method which indicates whether any network connection is available.

    Try this:

    bool connection = NetworkInterface.GetIsNetworkAvailable();
    if (connection == true)
     {
         MessageBox.Show("The system is online");
     }
     else {
         MessageBox.Show("The system is offline";
     }
    
    0 讨论(0)
  • 2020-11-22 08:29
    bool bb = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
    
    if (bb == true)
        MessageBox.Show("Internet connections are available");
    else
        MessageBox.Show("Internet connections are not available");
    
    0 讨论(0)
  • 2020-11-22 08:29

    For my application we also test by download tiny file.

    string remoteUri = "https://www.microsoft.com/favicon.ico"
    
    WebClient myWebClient = new WebClient();
    
    try
    {
        byte[] myDataBuffer = myWebClient.DownloadData (remoteUri);
        if(myDataBuffer.length > 0) // Or add more validate. eg. checksum
        {
            return true;
        }
    }
    catch
    {
        return false;
    }
    

    Also. Some ISP may use middle server to cache file. Add random unused parameter eg. https://www.microsoft.com/favicon.ico?req=random_number Can prevent caching.

    0 讨论(0)
  • 2020-11-22 08:29
    public static bool HasConnection()
    {
        try
        {
            System.Net.IPHostEntry i = System.Net.Dns.GetHostEntry("www.google.com");
            return true;
        }
        catch
        {
            return false;
        }
    }
    

    That works

    0 讨论(0)
  • 2020-11-22 08:31

    Something like this should work.

    System.Net.WebClient

    public static bool CheckForInternetConnection()
    {
        try
        {
            using (var client = new WebClient())
                using (client.OpenRead("http://google.com/generate_204")) 
                    return true; 
        }
        catch
        {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:34

    Here's how it is implemented in Android.

    As a proof of concept, I translated this code to C#:

    var request = (HttpWebRequest)WebRequest.Create("http://g.cn/generate_204");
    request.UserAgent = "Android";
    request.KeepAlive = false;
    request.Timeout = 1500;
    
    using (var response = (HttpWebResponse)request.GetResponse())
    {
        if (response.ContentLength == 0 && response.StatusCode == HttpStatusCode.NoContent)
        {
            //Connection to internet available
        }
        else
        {
            //Connection to internet not available
        }
    }
    
    0 讨论(0)
提交回复
热议问题