using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//使用DllImport需导入命名空间
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
namespace CheckNetwork
{
class Program
{
static void Main(string[] args)
{
bool isConn = IsConnectedInternet();
Console.ReadKey();
}
//导入判断网络是否连接的 .dll //判断网络状况的方法,返回值true为连接,false为未连接
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState( ref int Description, int ReservedValue);
/// <summary>
/// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败
/// </summary>
/// <returns></returns>
public static bool IsConnectInternet()
{
int Description = 0;
return InternetGetConnectedState(ref Description, 0);
}
/// <summary>
/// 判断本地的连接状态
/// </summary>
private static bool IsConnectedInternet()
{
int dwFlag = new int();
if (!InternetGetConnectedState( ref dwFlag, 0))
{
Console.WriteLine("当前没有联网,请您先联网后再进行操作!");
if ((dwFlag & 0x14) == 0) return false;
System.Diagnostics.Debug.WriteLine("本地系统处于脱机模式。");
return false;
}
else
{
if ((dwFlag & 0x01) != 0)
{
Console.WriteLine("调制解调器上网。");
return true;
}
else if ((dwFlag & 0x02) != 0)
{
Console.WriteLine("网卡上网。");
return true;
}
else if ((dwFlag & 0x04) != 0)
{
Console.WriteLine("代理服务器上网。");
return true;
}
else if ((dwFlag & 0x40) != 0)
{
Console.WriteLine("虽然可以联网,但可能链接也可能不连接。");
return true;
}
}
return false;
}
}
}