Home > Backend Development > C++ > How Can I Efficiently Verify Internet Connectivity in .NET?

How Can I Efficiently Verify Internet Connectivity in .NET?

Linda Hamilton
Release: 2025-01-25 19:52:14
Original
314 people have browsed it

How Can I Efficiently Verify Internet Connectivity in .NET?

Reliable Internet Connectivity Checks in .NET Applications

Ensuring reliable internet connectivity is paramount in today's networked world, particularly when dealing with geographically diverse users. This article presents an efficient and accurate method for verifying internet connectivity within .NET applications.

The following code snippet provides a robust solution:

<code class="language-csharp">public static bool CheckForInternetConnection(int timeoutMs = 10000, string url = null)
{
    try
    {
        url = url ?? CultureInfo.InstalledUICulture switch
        {
            { Name: var n } when n.StartsWith("fa") => "http://www.aparat.com", // Iran
            { Name: var n } when n.StartsWith("zh") => "http://www.baidu.com", // China
            _ => "http://www.gstatic.com/generate_204",
        };

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.KeepAlive = false;
        request.Timeout = timeoutMs;
        using (var response = (HttpWebResponse)request.GetResponse())
            return true;
    }
    catch
    {
        return false;
    }
}</code>
Copy after login

This function utilizes HttpWebRequest to attempt a connection to a specified URL. The KeepAlive property is set to false and a timeout is implemented to ensure efficient and responsive connectivity checks. Furthermore, the code intelligently handles potential regional restrictions by selecting appropriate URLs based on the user's current culture. This ensures a more reliable check across different geographical locations.

This approach provides developers with a dependable and efficient mechanism for verifying internet connectivity within their .NET applications.

The above is the detailed content of How Can I Efficiently Verify Internet Connectivity in .NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template