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

后端 未结 27 2357
感动是毒
感动是毒 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;
    }
    

提交回复
热议问题