¿Podría decirme si hay una manera de verificar si hay una conexión a Internet en mi computadora cuando mi progtwig C # está funcionando? Para un ejemplo simple, si Internet funciona, mostraría un cuadro de mensaje que dice que Internet is available
. de lo contrario, emitiría un mensaje diciendo: Internet is unavailable
.
Sin usar la función de biblioteca para ver si la red está disponible (ya que esto no comprueba la conectividad a Internet)
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
O sin abrir una página web y ver si está devolviendo datos
using (WebClient client = new WebClient()) htmlCode = client.DownloadString("http://google.com");
Porque estos dos métodos anteriores no satisfacen mis necesidades.
Una versión un poco más corta:
public static bool CheckForInternetConnection() { try { using (var client = new WebClient()) using (var stream = client.OpenRead("http://www.google.com")) { return true; } } catch { return false; } }
Otra opción es:
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) { // presumbly online }
Puedes encontrar una discusión más amplia aquí
Considere el siguiente fragmento de código …
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) { // presumbly online }
¡Buena suerte!
Acabo de escribir funciones asíncronas para hacer eso:
private void myPingCompletedCallback(object sender, PingCompletedEventArgs e) { if (e.Cancelled) return; if (e.Error != null) return; if (e.Reply.Status == IPStatus.Success) { //ok connected to internet, do something... } } private void checkInternet() { Ping myPing = new Ping(); myPing.PingCompleted += new PingCompletedEventHandler(myPingCompletedCallback); try { myPing.SendAsync("google.com", 3000 /*3 secs timeout*/, new byte[32], new PingOptions(64, true)); } catch { } }
Mi clase de NetworkMonitor ahora proporciona esto (basado en otras respuestas aquí):
public bool IsInternetAvailable { get { return IsNetworkAvailable && _CanPingGoogle(); } } private static bool _CanPingGoogle() { const int timeout = 1000; const string host = "google.com"; var ping = new Ping(); var buffer = new byte[32]; var pingOptions = new PingOptions(); try { var reply = ping.Send(host, timeout, buffer, pingOptions); return (reply != null && reply.Status == IPStatus.Success); } catch (Exception) { return false; } }
Este es mi enfoque;
Compruebe si podemos conectar con algunos de los principales hosts. Utilice una reserva en caso de que el sitio no esté disponible.
public static bool ConnectToInternet(int timeout_per_host_millis = 1000, string[] hosts_to_ping = null) { bool network_available = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable(); if (network_available) { string[] hosts = hosts_to_ping ?? new string[] { "www.google.com", "www.facebook.com" }; Ping p = new Ping(); foreach (string host in hosts) { try { PingReply r = p.Send(host, timeout_per_host_millis); if (r.Status == IPStatus.Success) return true; } catch { } } } return false; }
Notas:
public static bool HasConnection() { try { System.Net.IPHostEntry i = System.Net.Dns.GetHostEntry("www.google.com"); return true; } catch { return false; } }