判断计算机是否联网

-------第一种方法,这种方法比较常用也很简单

public partial class Form1 : Form
{
        //判断网络连接
        [DllImport("wininet")]
        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
        ///<summary>
        /// 检测本机的网络连接
        ///</summary>
 
       private void button1_Click(object sender, EventArgs e)
        {
            //判断是否联网
                int i = 0;
                if (InternetGetConnectedState(out i, 0))
                {
                    //联网
                    MessageBox.Show("Thylx提醒您:你的计算机已连接到网络上!");
                 }
                 else
                  {
                     //断网
                     MessageBox.Show("Thylx提醒您:本地连接已断开!");
                  }
        }
}

-----第二种方式

using System.Net.NetworkInformation;
namespace 判断是否联网
{
class program{
   static void Main(string[] args){
 Ping p = new Ping();
   PingReply pr;
  pr = p.Send("119.75.218.45");//百度的IP
 if (pr.Status != IPStatus.Success)//如果连接不成功
{
Console.WriteLine("未联网");
}else{
 Console.WriteLine("已联网");
}
   Console.Read();
}


}
}
 

 
原文地址:https://www.cnblogs.com/luoqin520/p/4660733.html