public async Task<bool> IsPortReachable(string host, int port = 80, int msTimeout = 5000) { return await Task.Run(async () => { var sockaddr = new InetSocketAddress(host, port); using (var sock = new Socket()) { try { await sock.ConnectAsync(sockaddr, msTimeout); return true; } catch (Exception) { return false; } } }); }
/// <summary> /// Tests if a remote host name is reachable /// </summary> /// <param name="host">Host name can be a remote IP or URL of website (no http:// or www.)</param> /// <param name="port">Port to attempt to check is reachable.</param> /// <param name="msTimeout">Timeout in milliseconds.</param> /// <returns></returns> public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); if (!IsConnected) return false; host = host.Replace("http://www.", string.Empty). Replace("http://", string.Empty). Replace("https://www.", string.Empty). Replace("https://", string.Empty); return await Task.Run(async () => { try { var sockaddr = new InetSocketAddress(host, port); using (var sock = new Socket()) { await sock.ConnectAsync(sockaddr, msTimeout); return true; } } catch (Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } }); }
/// <summary> /// Tests if a remote host name is reachable /// </summary> /// <param name="host">Host name can be a remote IP or URL of website (no http:// or www.)</param> /// <param name="port">Port to attempt to check is reachable.</param> /// <param name="msTimeout">Timeout in milliseconds.</param> /// <returns></returns> public override async Task<bool> IsRemoteReachable(string host, int port = 80, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); if (!IsConnected) return false; host = host.Replace("http://www.", string.Empty). Replace("http://", string.Empty). Replace("https://www.", string.Empty). Replace("https://", string.Empty); return await Task.Run(async () => { try { var tcs = new TaskCompletionSource<InetSocketAddress>(); new System.Threading.Thread(async () => { /* this line can take minutes when on wifi with poor or none internet connectivity and Task.Delay solves it only if this is running on new thread (Task.Run does not help) */ InetSocketAddress result = new InetSocketAddress(host, port); if (!tcs.Task.IsCompleted) tcs.TrySetResult(result); }).Start(); Task.Run(async () => { await Task.Delay(msTimeout); if (!tcs.Task.IsCompleted) tcs.TrySetResult(null); }); var sockaddr = await tcs.Task; if (sockaddr == null) return false; using (var sock = new Socket()) { await sock.ConnectAsync(sockaddr, msTimeout); return true; } } catch (Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } }); }