网络连接检测
1、ping的方式
2、[DllImport("winInet.dll ")]的方式
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net.Sockets;
namespace MyNetConnect
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int step = 0;
bool bIsConnectNet = IsConn2();
textBox1.Text += step.ToString() + ": "+bIsConnectNet.ToString() + System.Environment.NewLine;
}
/// <summary>
/// 用ping的返回值来测试有没有网络
/// 缺点:百度断网了就不行用了
/// </summary>
/// <example>
/// ping具体IP地址如"192.168.88.7",可以用来检测局域网连接
/// ping不通卡大约4.6-5s
/// </example>
/// <returns></returns>
public bool IsConn()
{
System.Net.NetworkInformation.Ping ping=new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply res;
try
{
//局域网
//string RemoteLAN = textBox2.Text;//"192.168.88.7"
//res = ping.Send(RemoteLAN);
string RemoteUrl = "www.baidu.com";
res = ping.Send(RemoteUrl);
if (res.Status != System.Net.NetworkInformation.IPStatus.Success)
return false;
else
return true;
}
catch (Exception er)
{
return false;
}
}
//InternetGetConnectedState返回的状态标识位的含义:
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 dwFlag, int dwReserved);
/// <summary>
/// 使用InternetGetConnectedState () 函数
/// 这个win32 API 在系统 system32 文件夹中 winInet.dll 中 ,可以用来判断是否联网和上网的方式是 Modem 还是 LAN 等
/// </summary>
/// <returns></returns>
private bool IsConn2()
{
int dwFlag = 0;
string netstatus = "";
if (!InternetGetConnectedState(ref dwFlag, 0))
textBox1.Text += "未联网!" + Environment.NewLine;
//Console.WriteLine("未联网!");
else
{
if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
{
netstatus += " 采用调治解调器上网 \n";
return true;
}
if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
{
netstatus += " 采用网卡上网 \n";
return true;
}
if ((dwFlag & INTERNET_CONNECTION_PROXY) != 0)
{
netstatus += " 采用代理上网 \n";
return true;
}
if ((dwFlag & INTERNET_CONNECTION_MODEM_BUSY) != 0)
{
netstatus += " MODEM被其他非INTERNET连接占用 \n";
return false;
}
textBox1.Text += netstatus + Environment.NewLine;
}
return false;
}
}
}