How to check internet connectivity in C#
By FoxLearn 12/27/2024 2:09:50 AM 140
However, it does not confirm if the connection is to the internet, as the network could be limited to a local network only. To verify internet connectivity, you can send an HTTP GET request to popular websites like microsoft.com or google.com.
The example described uses the Network Connectivity Status Indicator (NCSI) method, which is available in Windows OS (Vista and later). NCSI first attempts to reach the Microsoft NCSI test URL, and then checks the NCSI DNS IP address to ensure correct DNS configuration and validate internet connectivity.
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; public class InternetConnectionChecker { private const string NCSI_TEST_URL = "http://www.msftncsi.com/ncsi.txt"; private const string NCSI_TEST_RESULT = "Microsoft NCSI"; private const string NCSI_DNS = "dns.msftncsi.com"; private const string NCSI_DNS_IP_ADDRESS = "131.107.255.255"; public static async Task<bool> IsInternetConnectedAsync() { try { // Check NCSI test URL using HttpClient for async operations using (var client = new HttpClient()) { string result = await client.GetStringAsync(NCSI_TEST_URL); if (result != NCSI_TEST_RESULT) { return false; } } // Check NCSI DNS IP address var dnsHost = await Dns.GetHostAddressesAsync(NCSI_DNS); if (dnsHost.Length == 0 || dnsHost[0].ToString() != NCSI_DNS_IP_ADDRESS) { return false; } } catch (HttpRequestException ex) { // Handle specific web-related exceptions (HTTP request errors) Debug.WriteLine(ex); return false; } catch (SocketException ex) { // Handle DNS-related errors Debug.WriteLine(ex); return false; } catch (Exception ex) { // Catch any other unexpected errors Debug.WriteLine(ex); return false; } return true; } }
The IsInternetConnectedAsync
method uses asynchronous operations with HttpClient
for non-blocking I/O.
We specifically catch HttpRequestException
for web requests and SocketException
for DNS issues, which gives more targeted error handling.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#