如何使用.NET,C#和WPF检查Internet连接

Rag*_*nar 19 .net c# connection wpf

我正在使用.NET,C#和WPF,我需要检查连接是否打开到某个URL,我无法获得我在Internet上找到的任何代码.

我试过了:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
    IAsyncResult result = socket.BeginConnect("localhost/myfolder/", 80, null, null);
    bool success = result.AsyncWaitHandle.WaitOne(3000, true);
    if (!success)
    {
        MessageBox.Show("Web Service is down!");
    }
    else
        MessageBox.Show("Everything seems ok");
}
finally
{
    socket.Close();
}
Run Code Online (Sandbox Code Playgroud)

但即使我关闭了我的本地Apache服务器,我总是得到一切都正常的消息.

我也尝试过:

ing ping = new Ping();
PingReply reply;
try
{
    reply = ping.Send("localhost/myfolder/");
    if (reply.Status != IPStatus.Success)
        MessageBox.Show("The Internet connection is down!");
    else
        MessageBox.Show("Seems OK");
}
catch (Exception ex)
{
    MessageBox.Show("Error: " + ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

但这总是给出一个例外(ping似乎只能ping服务器,所以localhost工作但localhost/myfolder/doesnt)

请问如何检查连接,以便它对我有用?

Ana*_*bhi 27

许多开发人员只是通过ping Google.com来解决这个"问题".好...?:/这适用于大多数(99%)的情况,但是如何专业地将您的应用程序的工作依赖于某些外部Web服务?

有一个非常有趣的Windows API函数InternetGetConnectedState(),它可以识别您是否可以访问Internet ,而不是ping Google.com .

这种情况的解决方案是:

using System;
using System.Runtime;
using System.Runtime.InteropServices;
 
public class InternetAvailability
{
    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int description, int reservedValue);
 
    public static bool IsInternetAvailable( )
    {
        int description;
        return InternetGetConnectedState(out description, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @AnantDabhi 感谢您提供资源。此外,我还发现这个函数https://msdn.microsoft.com/en-us/library/windows/desktop/aa384346%28v=vs.85%29.aspx 完全符合Rowan所说的功能。如果需要,您也可以将其添加到您的回复中。 (2认同)

Rag*_*nar 23

最后我使用了自己的代码:

private bool CheckConnection(String URL)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        request.Timeout = 5000;
        request.Credentials = CredentialCache.DefaultNetworkCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        if (response.StatusCode == HttpStatusCode.OK)
            return true;
        else
            return false;
    }
    catch
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

一个有趣的事情是,当服务器关闭时(我关闭我的Apache)我没有获得任何HTTP状态,但抛出异常.但这足够好:)

  • 如果要检查HTTP状态,请抓住`WebException`异常并查看`Status`属性.还有一个名为"TimeOut"的项目. (3认同)
  • 最后,你可以这样做:`return(response.StatusCode == HttpStatusCode.OK);` (2认同)

Bal*_*a R 13

用这个:

private bool CheckConnection()
{
    WebClient client = new WebClient();
    try
    {
        using (client.OpenRead("http://www.google.com"))
        {
        }
        return true;
    }
    catch (WebException)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我已经使用了多年,但是当我们的一名开发人员被Google锁定时,由于他/她在一小时内向Google发送了5000多个请求,这将应用程序标记为拒绝服务攻击,因此遇到了一个问题。 (2认同)

小智 13

你可以试试这个;

private bool CheckNet()
{
    bool stats;
    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
    {
        stats = true;
    }
    else
    {
        stats = false;
    }
    return stats;
}
Run Code Online (Sandbox Code Playgroud)

  • +1因为它指向了NetworkInterface类.但是,如果*网络*已启动但*互联网访问*已关闭,我认为这不会起作用... (4认同)

Mah*_*man 8

我经历了所有的解决方案。NetworkInterface.GetIsNetworkAvailable()不检查互联网连接。它仅检查是否有可用的网络连接。

Ping不可靠,因为在许多网络中 ping 被关闭。使用 webclient 连接到 google 也不是 100% 可靠,如果您使用得太频繁,它也会产生性能开销。

对我来说使用Windows NLM API似乎是更好的解决方案。

using NETWORKLIST;

namespace Network.Helpers
{
    public class InternetConnectionChecker
    {
        private readonly INetworkListManager _networkListManager;

        public InternetConnectionChecker()
        {
            _networkListManager = new NetworkListManager();
        }

        public bool IsConnected()
        {
            return _networkListManager.IsConnectedToInternet;
        }
        
    }
}
Run Code Online (Sandbox Code Playgroud)

这是将其添加到项目中的方法。

在此输入图像描述


sus*_*ant 5

我认为,在Windows应用程序,Windows窗体或WPF应用程序中,这样做会更准确,而不是使用WebClient或HttpWebRequest,

public class InternetChecker
{
    [System.Runtime.InteropServices.DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

    //Creating a function that uses the API function...
    public static bool IsConnectedToInternet()
    {
        int Desc;
        return InternetGetConnectedState(out Desc, 0);
    }

}
Run Code Online (Sandbox Code Playgroud)

通话时写

if(InternetCheckerCustom.CheckNet())
{
  // Do Work 
}
else
{
  // Show Error MeassgeBox 
}
Run Code Online (Sandbox Code Playgroud)