C#判断网络连接状态

本人最近做c#winform的项目,遇到了判断网络是否正常连接的问题。后来查出了以下几种方法,供大家学习参考。
1.方法一
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
namespace WindowsFormsApplication1
{
    public partial class Demo : Form
    {
        public Demo()
        {
            InitializeComponent();
        }
        //判断
        private void btpanduan_Click(object sender, EventArgs e)
        {
            //210.192.120.228  163网易
            string ip = this.txtip.Text.ToString();
            int port = Convert .ToInt32( this.txtport.Text.ToString());
            bool a = panduan(ip, port );//135为本机服务端口号
            if (a == true)
            {
                MessageBox.Show("该网络连接正常 !");
            }
            else
            {
                MessageBox.Show("该网络连接不畅通 !");
            }
        }
      
      // 异步调用
 
        //判断的方法
        public bool panduan(string ip, int port)
        {
            try
            {
                TcpClient client = new TcpClient(ip, port);
                if (client.Connected)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
    }
}
 
2.利用 c# ping类
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;
namespace WindowsFormsApplication1
{
    public partial class Demo3 : Form
    {
        public Demo3()
        {
            InitializeComponent();
        }
        System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
        System.Net.NetworkInformation.PingReply res;
        //检查网络连接
        private void btcheck_Click(object sender, EventArgs e)
        {

            string url = this.txturl.Text.ToString();
            bool a = check(url);
            if (a == true)
            {
                MessageBox.Show("连接成功!", "提示信息");

            }
            else
            {
                MessageBox.Show("连接失败!", "提示信息");
            }
        }

        public bool check(string url)
        {

            try
            {
                res = ping.Send(url);
                if (res.Status == System.Net.NetworkInformation.IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch {

                return false;
            }
        }
    }
}
 

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.NetworkInformation;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            string url = "www.baidu.com;www.sina.com;www.cnblogs.com;www.google.com;www.163.com;www.csdn.com";
            string[] urls = url.Split(new char[] { ';' });
            CheckServeStatus(urls);

            Console.ReadKey();
        }
        
        /// 
        /// 检测网络连接状态
        /// 
        /// 
        public static void CheckServeStatus(string[] urls)
        {
            int errCount = 0;//ping时连接失败个数

            if (!LocalConnectionStatus())
            {
                Console.WriteLine("网络异常~无连接");
            }
            else if (!MyPing(urls, out errCount))
            {
                if ((double)errCount / urls.Length >= 0.3)
                {
                    Console.WriteLine("网络异常~连接多次无响应");
                }
                else
                {
                    Console.WriteLine("网络不稳定");
                }
            }
            else
            {
                Console.WriteLine("网络正常");
            }
        }

        #region 网络检测

         private const int INTERNET_CONNECTION_MODEM = 1;
        private const int INTERNET_CONNECTION_LAN = 2;

        [System.Runtime.InteropServices.DllImport("winInet.dll")]
        private static extern bool InternetGetConnectedState(ref int dwFlag, int dwReserved);

        /// 
        /// 判断本地的连接状态
         /// 
        /// 
        private static bool LocalConnectionStatus()
        {
            System.Int32 dwFlag = new Int32();
            if (!InternetGetConnectedState(ref dwFlag, 0))
            {
                Console.WriteLine("LocalConnectionStatus--未连网!");
                return false;
            }
            else
            {
                if ((dwFlag & INTERNET_CONNECTION_MODEM) != 0)
                {
                    Console.WriteLine("LocalConnectionStatus--采用调制解调器上网。");
                    return true;
                }
                else if ((dwFlag & INTERNET_CONNECTION_LAN) != 0)
                {
                    Console.WriteLine("LocalConnectionStatus--采用网卡上网。");
                    return true;
                }
            }
            return false;
        }

        /// 
        /// Ping命令检测网络是否畅通
        /// 
        /// URL数据
        /// ping时连接失败个数
        /// 
        public static bool MyPing(string[] urls, out int errorCount)
        {
            bool isconn = true;
            Ping ping = new Ping();
            errorCount = 0;
            try
            {
                PingReply pr;
                for (int i = 0; i < urls.Length; i++)
                {
                    pr = ping.Send(urls[i]);
                    if (pr.Status != IPStatus.Success)
                    {
                        isconn = false;
                        errorCount++;
                    }
                    Console.WriteLine("Ping " + urls[i] + "    " + pr.Status.ToString());
                }
            }
            catch
            {
                isconn = false;
                errorCount = urls.Length;
            }
            //if (errorCount > 0 && errorCount < 3)
            //  isconn = true;
            return isconn;
        }

        #endregion
    }
}




转自:http://www.2cto.com/kf/201204/128285.html

你可能感兴趣的:(Winform开发技术)