检查Internet连接状态 [英] Check Internet Connectivity Status

查看:141
本文介绍了检查Internet连接状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过c#检查Internet连接.我的计算机已与Network连接,仅Internet禁用.如何查找Internet连接状态.
以下代码不适合我的要求.即使仅连接了网络且已禁用Internet,它也会返回true.

I want to check the internet connectivity thro c#.My computer is connected with Network only internet is disabled.How do i find the internet connectivity status.
The following code is not suitable for my requirement.it returns true even only network is connected and internet disabled.

[DllImport("wininet.dll")]
  private extern static bool InternetGetConnectedState( out int Description, int ReservedValue );
  public static bool IsConnectedToInternet( )
  {
    int Desc ;
    return InternetGetConnectedState( out Desc, 0 ) ;
  }



此(以下)代码有效,但会花费更多时间并使我的应用程序挂起,



This(following) code works but takes more time and makes my application hangs,

System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://www.google.com");
                req.Method = "HEAD";

                System.Net.HttpWebResponse resp = (System.Net.HttpWebResponse)req.GetResponse();
                resp.Close(); return true;



还有其他检查互联网连接状态的好方法.



Is any other good way to check internet connectivity status.
All your Suggestions are appreciable!!!

推荐答案

如果您使用的是.net 4,请使用Ping以及8.8.8.8(Google的DNS) )
http://msdn.microsoft.com/en-us/library/system. net.networkinformation.ping.aspx [ ^ ]
If you are using .net 4, use Ping and an internet address like : 8.8.8.8 (Google''s DNS)
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping.aspx[^]


在使用第二种方法或Mehdi Gholam提供的解决方案时,您可能需要确保从某个线程执行此操作.不是您的主线程,因为这会导致UI挂起.
When using the second approach or the solution provided by Mehdi Gholam, you may want to make sure that you are doing this from a thread that is not your main thread since this would cause the UI to hang.


请参阅以下

http://www.c-sharpcorner.com/UploadFile/scottlysle/ConnectionState02092007002002552AM/ConnectionState.aspx [ ^ ]

http://stackoverflow.com/questions/5405895/how- to-check-internet-connection-with-net-c-wpf [
see these

http://www.c-sharpcorner.com/UploadFile/scottlysle/ConnectionState02092007002552AM/ConnectionState.aspx[^]

http://stackoverflow.com/questions/5405895/how-to-check-internet-connection-with-net-c-wpf[^]


这篇关于检查Internet连接状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆