C#中判断本地系统的网络连接状态的方法

时间:2021-05-20

函数InternetGetConnectedState返回本地系统的网络连接状态。

语法:

BOOL InternetGetConnectedState(__out LPDWORD lpdwFlags,__in DWORD dwReserved);参数:lpdwFlags[out]指向一个变量,该变量接收连接描述内容。该参数在函数返回FLASE时仍可以返回一个有效的标记。该参数可以为下列值的一个或多个。值含义INTERNET_CONNECTION_CONFIGURED0x40Local system has a valid connection to the Internet, but it might or might not be currently connected.INTERNET_CONNECTION_LAN 0x02Local system uses a local area network to connect to the Internet.INTERNET_CONNECTION_MODEM0x01Local system uses a modem to connect to the Internet.INTERNET_CONNECTION_MODEM_BUSY0x08No longer used.INTERNET_CONNECTION_OFFLINE 0x20Local system is in offline mode.INTERNET_CONNECTION_PROXY0x04Local system uses a proxy server to connect to the Internet.INTERNET_RAS_INSTALLED0x10Local 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();
}
}
}


截图:

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章