【C#源码】判断网络是否连接上

方法一:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Ping a = new Ping();
            PingReply re = a.Send("202.96.134.134");//得到PING返回值

            if (re.Status == IPStatus.Success)  //如果ping成功
            {
                label1.Text = "外网连接成功..";
                label1.ForeColor = Color.Green;
            }
            else
            {
                label1.Text = "外网连接失败";
                label1.ForeColor = Color.Red;
            }
        }
    }
}

 

方法二:

using System;
 using System.Runtime.InteropServices;
 
 namespace Network_status
 {
     class Program
     {
         [DllImport("wininet.dll", EntryPoint = "InternetGetConnectedState")]
         public extern static bool InternetGetConnectedState(out int conState, int reder);
         //参数说明 constate 连接说明 ,reder保留值
         public static bool IsConnectedToInternet()
         {
             int Desc=0;
             return InternetGetConnectedState(out  Desc, 0);
         }
         public static void Main(string[] args)
         {
             while(true)
             {
                  if (IsConnectedToInternet())
                  {
                     Console.WriteLine("已连接在网上!");
                     //通知我的Code....
                  }
                 else
                 {
                     Console.WriteLine("未连接在网上!"); 
                 }
                 System.Threading.Thread.Sleep(5000);
             }
         }
     }
 }

原创文章,转载请注明出处:http://www.cnblogs.com/hongfei

 

posted @ 2013-04-08 21:44  曾是土木人  阅读(1016)  评论(1编辑  收藏  举报