最近程序需要实时检测本地连接状态,在网上找到了两种方法,记录一下。
第一种方式:
[DllImport("sensapi.dll")]
private extern static bool IsNetworkAlive(out int connectionDescription);private string Fun_IsNetworkAlive()
{
int NETWORK_ALIVE_LAN = 0;
int NETWORK_ALIVE_WAN = 2;
int NETWORK_ALIVE_AOL = 4;
string outPut = null;
//上网方式
int flags;
//是否在线
bool m_bOnline = true;
m_bOnline = IsNetworkAlive(out flags);
//在线
if (m_bOnline)
{
if ((flags & NETWORK_ALIVE_LAN) == NETWORK_ALIVE_LAN)
{
outPut = "已连接LAN";
}
if ((flags & NETWORK_ALIVE_WAN) == NETWORK_ALIVE_WAN)
{
outPut = "已连接WAN";
}
if ((flags & NETWORK_ALIVE_AOL) == NETWORK_ALIVE_AOL)
{
outPut = "已连接AOL";
}
}
else
{
outPut = "连接中断!";
}
return outPut;
}
第二种方式:
[DllImport("winInet.dll ")]
//声明外部的函数:
private static extern bool InternetGetConnectedState(
ref int Flag,
int dwReserved
);
private string CheckStatus()
{
int Flag = 0;
string netStates = "";
if (!InternetGetConnectedState(ref Flag, 0))
{
netStates = "本地连接已断开!";
}
else
{
if ((Flag & INTERNET_CONNECTION_MODEM) != 0)
netStates += "已连接到调制解调器";
if ((Flag & INTERNET_CONNECTION_LAN) != 0)
netStates += "已连接LAN";
if ((Flag & INTERNET_CONNECTION_PROXY) != 0)
netStates += "已连接PROXY";
if ((Flag & INTERNET_CONNECTION_MODEM_BUSY) != 0)
netStates += "调制解调器busy";
}
return netStates;
}