以编程方式检查互联网连接是否可用的最简单方法是什么?
编辑:建议我尝试使用以下方法,但它总是返回true.
[Flags]
enum InternetConnectionState : int
{
INTERNET_CONNECTION_MODEM = 0x1,
INTERNET_CONNECTION_LAN = 0x2,
INTERNET_CONNECTION_PROXY = 0x4,
INTERNET_RAS_INSTALLED = 0x10,
INTERNET_CONNECTION_OFFLINE = 0x20,
INTERNET_CONNECTION_CONFIGURED = 0x40
}
class Program
{
[DllImport("WININET", CharSet = CharSet.Auto)]
static extern bool InternetGetConnectedState(ref InternetConnectionState lpdwFlags, int dwReserved);
static void Main(string[] args)
{
InternetConnectionState flags = 0;
bool isConnected = InternetGetConnectedState(ref flags, 0);
Console.WriteLine(isConnected);
//Console.WriteLine(flags);
Console.ReadKey();
}
}
Run Code Online (Sandbox Code Playgroud)
附加信息(如果有帮助):我通过共享的无线网络访问互联网.
col*_*ium 21
这是您可以调用的Windows API.它位于wininet.dll中并称为InternetGetConnectedState.
using System;
using System.Runtime;
using System.Runtime.InteropServices;
public class InternetCS
{
//Creating the extern function...
[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)
小智 10
Microsoft Windows Vista和7使用NCSI(网络连接状态指示器)技术:
NCSI在www.msftncsi.com上执行DNS查找,然后请求http://www.msftncsi.com/ncsi.txt.此文件是纯文本文件,仅包含文本"Microsoft NCSI".NCSI发送dns.msftncsi.com的DNS查找请求.此DNS地址应解析为131.107.255.255.如果地址不匹配,则假定互联网连接无法正常运行.
您可以在.NET 2.0+中使用它来检查网络连接
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
Run Code Online (Sandbox Code Playgroud)
这可能只会返回true本地网络,因此它可能不适合您.
这是我到目前为止找到的最佳解决方案:
public static bool isConnected()
{
try
{
string myAddress = "www.google.com";
IPAddress[] addresslist = Dns.GetHostAddresses(myAddress);
if (addresslist[0].ToString().Length > 6)
{
return true;
}
else
return false;
}
catch
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
if(isConnected())
{
//im connected to the internet
}
else
{
//not connected
}
Run Code Online (Sandbox Code Playgroud)
这是一个问题,答案真的是"它取决于".因为这取决于您要检查的原因以及连接的类型?您希望能够通过http访问某些网站/服务吗?发送smtp邮件?dns查找?
使用先前答案的组合可能是要走的路 - 首先使用来自colithium的答案的wininet api来检查是否有任何类型的连接可用.
如果是,请尝试几个dns查找(请参阅System.Net.Dns),查找您感兴趣的资源或一些流行的大型网站(google,altavista,compuserve等等).
接下来,您可以尝试ping(请参阅Roger Willcocks的回答)和/或建立到相同站点的套接字连接.请注意,ping失败只是意味着防火墙规则不允许您ping.
如果您可以更具体地了解为什么要检查它,将更容易提供满足您要求的答案...