Home > Backend Development > C++ > How Can I Quickly Verify Network Connectivity in .NET?

How Can I Quickly Verify Network Connectivity in .NET?

Linda Hamilton
Release: 2025-01-25 19:37:09
Original
499 people have browsed it

How Can I Quickly Verify Network Connectivity in .NET?

The fastest way to verify .NET network connection

In .NET application development, it is critical to determine the best technique for network connection verification. In scenarios where access to the Internet is required, a reliable and efficient mechanism is crucial. This article provides an effective solution to this need.

Use reliable connection check

To ensure reliable connection testing, consider the following code snippet:

<code class="language-csharp">public static bool CheckForInternetConnection(int timeoutMs = 10000, string url = null)
{
    try
    {
        url ??= CultureInfo.InstalledUICulture switch
        {
            { Name: var n } when n.StartsWith("fa") => // 伊朗
                "http://www.aparat.com",
            { Name: var n } when n.StartsWith("zh") => // 中国
                "http://www.baidu.com",
            _ =>
                "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

The above is the detailed content of How Can I Quickly Verify Network 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