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

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

    There is absolutely no way you can reliably check if there is an internet connection or not (I assume you mean access to the internet).

    You can, however, request resources that are virtually never offline, like pinging google.com or something similar. I think this would be efficient.

    try { 
        Ping myPing = new Ping();
        String host = "google.com";
        byte[] buffer = new byte[32];
        int timeout = 1000;
        PingOptions pingOptions = new PingOptions();
        PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
        return (reply.Status == IPStatus.Success);
    }
    catch (Exception) {
        return false;
    }
    
    0 讨论(0)
  • 2020-11-22 08:21

    Try to avoid testing connections by catching the exception. because we really Expect that sometimes we may lose network connection.

     if (NetworkInterface.GetIsNetworkAvailable() &&
         new Ping().Send(new IPAddress(new byte[] { 8, 8, 8, 8 }),2000).Status == IPStatus.Success)
     //is online
     else
     //is offline
    
    0 讨论(0)
  • 2020-11-22 08:24
    public static bool Isconnected = false;
    
    public static bool CheckForInternetConnection()
    {
        try
        {
            Ping myPing = new Ping();
            String host = "google.com";
            byte[] buffer = new byte[32];
            int timeout = 1000;
            PingOptions pingOptions = new PingOptions();
            PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
            if (reply.Status == IPStatus.Success)
            {
                return true;
            }
            else if (reply.Status == IPStatus.TimedOut)
            {
                return Isconnected;
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }
    
    public static void CheckConnection()
    {
        if (CheckForInternetConnection())
        {
            Isconnected = true;
        }
        else
        {
            Isconnected = false;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 08:25

    I am having issue on those method on my 3g Router/modem, because if internet is disconnected the router redirects the page to its response page, so you still get a steam and your code think there is internet. Apples (or others) have a hot-spot-dedection page which always returns a certain response. The following sample returns "Success" response. So you will be exactly sure you could connect the internet and get real response !

    public static bool CheckForInternetConnection()
    {
        try
        {       
            using (var webClient = new WebClient())
            using (var stream = webClient.OpenRead("http://captive.apple.com/hotspot-detect.html"))
            {
                if (stream != null)
                {
                    //return true;
                    stream.ReadTimeout = 1000;
                    using (var reader = new StreamReader(stream, Encoding.UTF8, false))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            if (line == "<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>")
                            {
                                return true;
                            }
                            Console.WriteLine(line);
                        }
                    }
    
                }
                return false;
            }
        }
        catch
        {
    
        }
        return false;
    }
    
    0 讨论(0)
  • 2020-11-22 08:27

    Another option is the Network List Manager API which is available for Vista and Windows 7. MSDN article here. In the article is a link to download code samples which allow you to do this:

    AppNetworkListUser nlmUser = new AppNetworkListUser();
    Console.WriteLine("Is the machine connected to internet? " + nlmUser.NLM.IsConnectedToInternet.ToString());
    

    Be sure to add a reference to Network List 1.0 Type Library from the COM tab... which will show up as NETWORKLIST.

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

    NetworkInterface.GetIsNetworkAvailable is very unreliable. Just have some VMware or other LAN connection and it will return wrong result. Also about Dns.GetHostEntry method I were just concerned about whether test URL might be blocked in the environment where my application going to deploy.

    So another way I found out is using InternetGetConnectedState method. My code is

    [System.Runtime.InteropServices.DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
    
    public static bool CheckNet()
    {
         int desc;
         return InternetGetConnectedState(out desc, 0);         
    }
    
    0 讨论(0)
提交回复
热议问题