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

后端 未结 27 2341
感动是毒
感动是毒 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:44

    The accepted answer succeeds quickly but is very slow to fail when there is no connection. So I wanted to build a robust connection check that would fail faster.

    Pinging was said to not be supported in all environments, so I started with the accepted answer and added a WebClient from here with a custom timeout. You can pick any timeout, but 3 seconds worked for me while connected via wifi. I tried adding a fast iteration (1 second), then a slow iteration (3 seconds) if the first one fails. But that made no sense since both iterations would always fail (when not connected) or always succeed (when connected).

    I'm connecting to AWS since I want to upload a file when the connection test passes.

    public static class AwsHelpers
    {
        public static bool GetCanConnectToAws()
        {
            try
            {
                using (var client = new WebClientWithShortTimeout())
                using (client.OpenRead("https://aws.amazon.com"))
                    return true;
            }
            catch
            {
                return false;
            }
        }
    }
    
    public class WebClientWithShortTimeout: WebClient
    {
        protected override WebRequest GetWebRequest(Uri uri)
        {
            var webRequest = base.GetWebRequest(uri);
            webRequest.Timeout = 5000;
            return webRequest;
        }
    }
    

提交回复
热议问题