C#中判断本地系统的网络连接状态的方法
时间:2023-07-02 15:39:41
函数InternetGetConnectedState返回本地系统的网络连接状态。
语法:
BOOL InternetGetConnectedState(
__out LPDWORD lpdwFlags,
__in DWORD dwReserved
);
参数:
lpdwFlags[out]
指向一个变量,该变量接收连接描述内容。该参数在函数返回FLASE时仍可以返回一个有效的标记。该参数可以为下列值的一个或多个。
值 | 含义 |
---|---|
INTERNET_CONNECTION_CONFIGURED0x40 | Local system has a valid connection to the Internet, but it might or might not be currently connected. |
INTERNET_CONNECTION_LAN 0x02 | Local system uses a local area network to connect to the Internet. |
INTERNET_CONNECTION_MODEM0x01 | Local system uses a modem to connect to the Internet. |
INTERNET_CONNECTION_MODEM_BUSY0x08 | No longer used. |
INTERNET_CONNECTION_OFFLINE 0x20 | Local system is in offline mode. |
INTERNET_CONNECTION_PROXY0x04 | Local system uses a proxy server to connect to the Internet. |
INTERNET_RAS_INSTALLED0x10 | Local system has RAS installed. |
dwReserved[in]
保留值。必须为0。
返回值:
当存在一个modem或一个LAN连接时,返回TRUE,当不存在internet连接或所有的连接当前未被激活时,返回false。
当该函数返回false时,程序可以调用GetLastError来接收错误代码。
示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
private const int INTERNET_CONNECTION_MODEM = 1;
private const int INTERNET_CONNECTION_LAN = 2;
private const int INTERNET_CONNECTION_PROXY = 4;
private const int INTERNET_CONNECTION_MODEM_BUSY = 8;
[DllImport("winInet.dll ")]
//声明外部的函数:
private static extern bool InternetGetConnectedState(
ref int Flag,
int dwReserved
);
static void Main(string[] args)
{
int Flag = 0;
string netStates = "";
if (!InternetGetConnectedState(ref Flag, 0))
{
Console.WriteLine("no!");
}
else
{
if ((Flag & INTERNET_CONNECTION_MODEM) != 0)
netStates += " Connect by MODEM /n";
if ((Flag & INTERNET_CONNECTION_LAN) != 0)
netStates += "Connect by LAN /n";
if ((Flag & INTERNET_CONNECTION_PROXY) != 0)
netStates += "Connect by PROXY /n";
if ((Flag & INTERNET_CONNECTION_MODEM_BUSY) != 0)
netStates += " MODEM is busy /n";
}
Console.WriteLine(netStates);
Console.ReadLine();
}
}
}