How to Redial ADSL Dial-up Connection by CSharp

  On the below, it is the C# class of connect and disconnect ADSL dial-up connection. We can use this class to redial ADSL connection. One can use ras.Connect("ADSL") to connect, and ras.Disconnect() to disconnect. Meanwhile, there are some tips of this class.

1. If you find that ras.Connect("ADSL") is of no effect, you need to conceal the dialog of ADSL dial-up connection, which can be set on Windows.

2. The object of this class just can be use only once, so you need to state the new one when you want to redial again.


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Net;
using System.IO;
using decoder;
using System.Threading;
using System.Net.NetworkInformation;

namespace ImeiSearch
{
    public partial class frmMain : Form
    {

        
        #region 常量定义区
            private const int RST_OK               = 0;                                //函数执行成功返回值
            private const int RST_ERR              = 1;                                //函数执行失败返回值
            private const int RST_NETERR           = 2;                                //网络异常
            private const string STR_ERROR         = "error";
            private const string POSTIMEI          = @"imei={0}&captext={1}";          //格式化提交的参数
            private const string NODENAME          = @"name='{0}' value='";            //待查找的节点名称字符串
            
            //<input type='hidden' name='brandc' value=''>
            private const string BRANDC            = "brandc";

            //<input type='hidden' name='manufacturerc' value='SHENZHEN SUNUP COMMUNICATION TECHNOLOGY CO LTD'>
            private const string MANUFACTURERC     = "manufacturerc";

            //<input type='hidden' name='tacc' value='86532700'>
            private const string TAAC              = "tacc";

            //<input type='hidden' name='modelc' value='Y999'>
            private const string MODELC            = "modelc";
            
            //<input type='hidden' name='imeic' value='86532700'>
            private const string IMEIC             = "imeic";

            //<input type='hidden' name='bandc' value='GSM 1800,GSM 900'>
            private const string BANDC             ="bandc";

            //<input type='hidden' name='insert_id' value='131745'>
            private const string INSERTID          ="insert_id";

            //<input type='hidden' name='information' value='true'>
            private const string INFORMATION       = "information";

        #endregion

        #region 变量定义区
            HttpWebResponse resp;                                           //获取验证码的一对WEB对象
            HttpWebRequest req;                                             //获取验证码返回的对象,处理获得验证码图片
            string strPath = string.Empty;                                  //保存当前exe的目录;
            string strBitmapPath = string.Empty;                            //验证码图片的保存位置
            string strHtmlPath = string.Empty;                              //保存HTML文件的目录
            private int imeiIdx = 0;                                        //获得IMEI的起始ID
            FileManage fm;                                                  //文集管理对象
            decodeHelper dh = new decodeHelper();                           //解析验证码的对象
            private List<string> strIpList = new List<string>();            //保存读取的csv文件数据
            private string strIP = string.Empty;                            //本地IP地址
            string cookieHeader;
            int count = 0;                                                  //获取连接状态的失败次数
        #endregion

        #region 窗体组件函数定义区

                /// <summary>
                /// 窗体加载初始化函数,初始化窗体组件,初始化文件路径以及建立存储验证码图片的文件夹
                /// </summary>
                public frmMain()
                {
                    InitializeComponent();                                                     //初始化窗体的组件
                    
                    //初始化验证码解析对象的消息事件
                    dh.OnShowMessage += new decodeHelper.showMessageEvent(dh_OnShowMessage);   //初始化解析验证码事件声明
                    
                    //验证码显示组件属性设置,验证码大小100 × 50
                    picVerification.SizeMode = PictureBoxSizeMode.StretchImage;                //设置验证码图片PIC的显示属性,子适应大小

                    //获取启动文件的路径,如果获取的启动文件路径不以\结尾,则增加一个结尾符号
                    strPath = Application.StartupPath;                                          //获得存储log文件的路径,如果不以"\"结尾,则增加"\"字符
                    if (strPath.EndsWith(@"\") == false)
                    {
                        strPath = strPath + @"\";
                    }

                    //建立文件夹,保存申请的验证码图片
                    strBitmapPath = strPath + @"VerifyCode\";                                   //设置验证码图片文件夹路径
                    if (false == Directory.Exists(strBitmapPath) )                              //判断文件夹是否存在,如果不存在则创建一个新的文件夹
                    {
                        Directory.CreateDirectory(strBitmapPath);                               //创建一个文件夹

                    }

                    //建立保存HTML文件的目录
                    strHtmlPath = strPath + @"html\";                                   //设置验证码图片文件夹路径
                    if (false == Directory.Exists(strHtmlPath))                              //判断文件夹是否存在,如果不存在则创建一个新的文件夹
                    {
                        Directory.CreateDirectory(strHtmlPath);                               //创建一个文件夹

                    }




                    timSearchInfo.Stop();
                    timerGetIP.Stop();

                    printMessage("Start Software!"); //提示程序启动

                    setStartEnable(true);//设置启动按钮可用,停止按钮不可用

                }

                /// <summary>
                /// 加载CSV文件数据到内存数据库中并显示在界面上,然后启动定时器开始根据IMEI查询厂家等信息
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void btnCommit_Click(object sender, EventArgs e)
                {

                    string strOpenFile = string.Empty;                              //打开的CSV文件路径

                    //文件打开对象初始化工作
                    openFileDialog_xls.Title = "加载IMEI文件对话框";
                    openFileDialog_xls.InitialDirectory = strPath;                  //设置默认的打开路径为EXE启动路径
                    openFileDialog_xls.Filter = @"CSV文件(*.csv)|*.csv";            //只能选择CSV文件

                    //获取CSV文件路径操作
                    if (openFileDialog_xls.ShowDialog() == DialogResult.OK)         //选择正确的CSV文件
                    {
                        strOpenFile = openFileDialog_xls.FileName;                  //取得选择的CSV文件路径(完整的路径和文件名)
                    }
                    else
                    {
                        return;                                                     //选择的时候点击对话框的取消按钮
                    }

                    //加载CSV文件中的数据
                    fm = new FileManage(strOpenFile);
                    
                    //加载CSV文件成功,启动定时器开始查询IMEI对于的厂家,型号等信息
                    if (true == fm.GetTotalIMEINumber())
                    {
                        //把加载到内存中的IMEI信息显示到LIST中
                        dispIMEI();

                        //启动时钟,准备查询IMEI对应的厂家等信息
                        
                        timSearchInfo.Start();

                        printMessage("Start search information for phone!");

                        setStartEnable(false);//设置启动按钮不可用,停止按钮可用

                        //马上执行动作
                        //timSearchInfo_Tick(this,new EventArgs());
                    }



                }

                private void btnStop_Click(object sender, EventArgs e)
                {

                    printMessage("Stop search information for phone!");
                    setStartEnable(true);//设置启动按钮可用,停止按钮不可用

                    
                    //停止定时器
                    timSearchInfo.Stop();
                    timerGetIP.Stop();

                    //初始化变量
                    int iflag = 0;
                    string strShow = "Have searched number of IMEI:";

                    this.Cursor = Cursors.WaitCursor;                               // 鼠标状态为等待状态
                     try
                     {
                         //保存CSV文件
                         iflag = fm.updateCSVFile();
                         strShow = strShow + iflag.ToString();
                         printMessage(strShow);

                     }
                     catch (Exception ex)
                     {
                         printMessage(ex.ToString());
                     }
                     finally
                     {
                         this.Cursor = Cursors.Default;                                   // resume the cursor;
                     }

                }

                /// <summary>
                /// 重载验证码图片操作
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void lkbReflash_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
                {
                    reflashImage();                                                 //刷新验证码
                }

                /// <summary>
                /// 解析验证码图片对象的消息事件
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                void dh_OnShowMessage(object sender, clsEventArgs e)
                {
                    //
                }

                /// <summary>
                /// 等待网络连接正常的时钟
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void timerGetIP_Tick(object sender, EventArgs e)
                {

                    if (true == isConnect("huawei.com"))
                    {
                        timerGetIP.Stop();
                        timSearchInfo.Start();
                        count = 0 ;                 //清除计数器,是否有用?
                    }

                    //连续失败5次,自动再尝试拨号
                    if ((count++) >= 10)
                    {
                        count = 0 ;                                         //清楚计数器
                        printMessage("have wait 20s,but network is down!"); //提示等待25秒,但是网络还是异常
                        ReDial();                                           //程序自动再拨号
                    }
                }

                /// <summary>
                /// 获取查询信息定时器触发函数
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void timSearchInfo_Tick(object sender, EventArgs e)
                {
                    string strImei = string.Empty;
                    string strVerification = string.Empty;
                    string postData = string.Empty;             // save the update data;
                    string rst = string.Empty;                  // save the return website information;
                    string strBrand = string.Empty;             //品牌信息
                    string strManufacturer = string.Empty;      //厂家信息
                    string strModel = string.Empty;             //型号信息
                    string strOS = string.Empty;                //操作系统信息
                    int intGetVerification = -1;                // Save Result for get Verification


                    //判断是否已经处理完毕IMEI,如果处理完毕则打印处理完毕的信息,停止查询时钟
                    if (imeiIdx >= fm.stImeiInfo.Count)
                    {
                        //打印处理完毕的信息
                        printMessage("have deal with all IMEIs!");
                        timSearchInfo.Stop();
                        return;
                    }

                    //获取验证码图片操作
                    intGetVerification = reflashImage();

                    //如果获取的验证码图片失败,可能是网络不通,也可能是其他原因。一般是网络不通造成的
                    switch (intGetVerification)
                    {
                        case RST_NETERR:            //网络异常
                            DealnetErr();          //处理网络异常
                            return;
                        case RST_ERR:               //一般意义的异常,需要从新获得验证码
                            return;

                    }

                    //验证码图片获取成功处理代码
                    if (intGetVerification == RST_OK)
                    {
                        // 获得验证码文字
                        dh.getDecodeString(6, ref strVerification);

                        //获取验证码文字失败,则返回,等待下一个时钟周期
                        if (strVerification == string.Empty) return;

                        //显示验证码文字
                        txtVerification.Text = strVerification;

                        //获取一个IMEI号码,准备处理
                        strImei = fm.GetAnIMEINumber(imeiIdx);

                        //IMEI号是否为空判断,如果为空,则进入下一个周期,很少出现,没有必要循环获取不为空的IMEI
                        if (strImei == string.Empty) return;

                        //获取查询数据操作
                        //"imei=" + strImei + "&captext=" + strVerification;
                        postData = string.Format(POSTIMEI, strImei, strVerification);  //拼装查询字符串                       
                        rst = PostWebRequest(@"http://imei-number.com/imei-lookup/", postData, Encoding.ASCII); // read the network content;

                        //查询的数据为空,则进入下一个循环周期
                        if (rst == string.Empty) return;

                        //保存查询到的数据,这个数据为XML格式,保存为HTML文件,可用网页现实打开校验
                        saveWebResponse(rst, strImei);

                        //获取到查询的数据,做数据分析处理
                        //有效的返回
                        if (rst.Contains("If you have different phone or device with this IMEI"))
                        {
                            //取得品牌,厂家以及型号信息,其中厂家允许最大长度200字符
                            strBrand = getImeiInfoFromString(rst, BRANDC, 30);
                            strManufacturer = getImeiInfoFromString(rst, MANUFACTURERC, 200);
                            strModel = getImeiInfoFromString(rst, MODELC, 30);

                            //品牌是否为空判断,如果品牌值为空,则吧厂家信息作为品牌存储起来
                            if (strBrand == "" || strBrand == STR_ERROR)
                            {
                                strBrand = strManufacturer;            //先复制厂家的信息作为品牌

                                //如果厂家的信息为空或者失败,则认为这个IMEI没有查询到对应的信息
                                if (strManufacturer == "" || strManufacturer == STR_ERROR)
                                {
                                    strBrand = "NO MATCH FOR THIS IMEI";
                                }

                            }

                        }
                        //没有查询到对于的厂家,型号,品牌等信息
                        else if (rst.Contains("NO MATCH FOR THIS IMEI"))
                        {
                            strBrand = "NO MATCH FOR THIS IMEI";
                        }
                        //这个是验证码错误,可能是因为会话不一致导致的错误,也可能是网站服务器的问题
                        else if (rst.Contains("CAPTCHA text ERROR! Try again"))
                        {
                            return; //等待小一个循环周期继续
                        }
                        //其他的异常,则需要再拨号获取新的IP地址,一般是网络异常,IP地址被封,查询次数到限制
                        //通常不会进入这个else,因为一旦发生这种情况,之前应该无法获取到验证码图片
                        else
                        {
                           DealnetErr();  //处理网络异常
                            return;
                        }


                        //更新内存数据库的数据,即使失败,也要循环下一个IMEI
                        if (false == fm.UpdateIMEIInfo(imeiIdx, strBrand, strModel, string.Empty, string.Empty, true, false, false))
                        {
                            printMessage(string.Format("Update the information of phone fail(IMEI={0})!", strImei));
                        }

                        //界面显示被处理成功,设置被选中
                        if (imeiIdx < lstIMEI.Items.Count)
                        {
                            lstIMEI.SelectedIndex = imeiIdx;
                            lstIMEI.SetItemChecked(imeiIdx, true);
                            
                        }

                        // 下一个IMEI
                        imeiIdx++;

                    }

                }



        #endregion

        #region 自定义函数区
                

                /// <summary>
                /// 设置启动按钮的状态
                /// </summary>
                /// <param name="blnEnable"></param>
                private void setStartEnable(bool blnEnable)
                {
                    btnCommit.Enabled = blnEnable;
                    btnStop.Enabled = (!blnEnable);
                }

                /// <summary>
                /// 显示从CSV文件中加载的IMEI到LIST中
                /// </summary>
                private void dispIMEI()
                {
                    int idx = 0 ;            //循环变量 
                    lstIMEI.Items.Clear();      //清空待显示的区域
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;                                            //改变鼠标形状为等待
                        //循环所有的IMEI,这些IMEI都没有被查询过,或者查询没有成功
                        for (idx = 0; idx < fm.stImeiInfo.Count; idx++)
                        {
                            lstIMEI.Items.Add(fm.stImeiInfo[idx].strImeiNumber);
                        }

                    }
                    catch (System.Exception ex)
                    {
                    	
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;                                            //改变鼠标形状为默认

                    }



                    //存在有效的IMEI,在LIST中已经被加载了IMEI,第一个IMEI被选择作为初始化
                    //if (idx != 0 )
                    //{
                     //   lstIMEI.SelectedIndex = 0;
                    //}

                }

                /// <summary>
                /// 获得验证码图片并且显示在界面,获取的过程中,鼠标变成等待状态
                /// </summary>
                private int reflashImage()
                {
                    int rst = RST_ERR;   //初始化返回结果,返回异常
                    try
                    {
                        //改变鼠标形状为等待
                        this.Cursor = Cursors.WaitCursor;

                        //设置获取验证码的URL
                        string strURL = "http://imei-number.com/captcha/mycaptchaimage.png";

                        //请求验证码图片对象初始化
                        req = (HttpWebRequest)HttpWebRequest.Create(strURL);
                        // req.Timeout = 1500;                                             //设置超时等待1.5S,the default time is 100s
                        req.KeepAlive = true;

                        //请求COOKER对象初始化
                        CookieCollection myCookies = null;
                        CookieContainer myCookieContainer = new CookieContainer();

                        //设置保存的COOKER
                        req.CookieContainer = myCookieContainer;

                        //请求信息的对象操作,获取验证码图片并且显示在界面上
                        using (resp = (HttpWebResponse)req.GetResponse())                       //获得返回码
                        {
                            cookieHeader = req.CookieContainer.GetCookieHeader(new Uri(strURL));
                            myCookies = resp.Cookies;

                            //获取到验证码图片对象,再显示之
                            Image img = new System.Drawing.Bitmap(resp.GetResponseStream());

                            //获取图片对象为空,直接返回异常
                            if (img == null)
                            {
                                this.Cursor = Cursors.Default;      //改变鼠标形状为正常
                                return rst;
                            }
                            picVerification.Image = img;            //显示验证码图片
                            //img.Save(strBitmapPath);              //保存验证码图片,现在不用保存

                            //准备做验证码识别处理 
                            Bitmap bmp = new Bitmap(img);
                            if (bmp == null) return rst;                                     //图片转换失败,直接返回异常

                            //初始化验证码识别对象,传入图片准备识别
                            dh.addBmpImage(bmp);

                            // 关闭返回对象
                            resp.Close();
                        }

                        //刷新界面,为了显示验证码图片
                        printMessage("Get the Verification picture OK!");        //成功获得,提示信息
                        this.Refresh();                                                  //刷新窗体

                        rst = RST_OK;

                    }
                    catch (Exception ex)
                    {
                        printMessage(ex.ToString());      //提示失败
                        rst = RST_NETERR;
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;                                   //改变鼠标形状为正常
                    }
                    return rst;
                }

                /// <summary>
                /// 提交数据后,获得返回结果。
                /// </summary>
                /// <param name="postUrl">提交的URL</param>
                /// <param name="paramData">提交的数据</param>
                /// <param name="dataEncode"></param>
                /// <returns></returns>
                private string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
                {

                    string ret = string.Empty;
                    string strImei = paramData.Substring(5, 8); //取得IMEI
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;                                            //改变鼠标形状为等待

                        //提交参数设置
                        byte[] byteArray = dataEncode.GetBytes(paramData);                           //转化提交的参数为字节
                        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl)); //创建一个HttpWebRequest
                        CookieContainer myCookieContainer = new CookieContainer();                   //初始化一个COOKER

                        //如果COOKER有数据,则沿用以前的COOKER做提交动作
                        if (cookieHeader.Length > 0)
                        {
                            myCookieContainer.SetCookies(new Uri(postUrl), cookieHeader);
                            webReq.CookieContainer = myCookieContainer;
                        }

                        //提交参数设置
                        webReq.Method = "POST";                                                      //提交类型为POST
                        webReq.ContentType = "application/x-www-form-urlencoded";                    //内容的类型
                        webReq.Timeout = 6000;
                        webReq.KeepAlive = true;
                        webReq.ContentLength = byteArray.Length;                                     //设定内容长度

                        //获取提交后返回的字符串流(HTML元代码)
                        Stream newStream = webReq.GetRequestStream();                                //获得请求的写入文件流
                        newStream.Write(byteArray, 0, byteArray.Length);                             //写入参数

                        HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();                     //提交数据获得返回对象HttpWebResponse
                        StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);//获得返回的字符流
                        ret = sr.ReadToEnd();                                                              //读取全部的字符
                        printMessage(string.Format("Get information successful[{0}]!", strImei));
                        sr.Close();                                                                        //关闭读字符流的对象
                        response.Close();                                                                  //释放对象 
                        newStream.Close();                                                                 //释放对象
                    }
                    catch (Exception ex) //异常处理入口
                    {
                        //不做处理,最后统一提示
                    }
                    finally
                    {
                        this.Cursor = Cursors.Default;                                     //改变鼠标形状为正常
                    }

                    //没有查询到数据,打印异常日志
                    if (ret == string.Empty)
                    {
                        printMessage(string.Format("Get information Fail[{0}]!", strImei));
                    }

                    return ret;                                                        //返回结果
                }
                
                
                /// <summary>
                /// 显示日志
                /// </summary>
                /// <param name="strMsg"></param>
                private void printMessage(string strMsg)
                {
                    //格式化显示的字符串信息
                    string t_strMsg = string.Format("[{0}]:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), strMsg);

                    //添加一条记录
                    lstMessage.Items.Add(t_strMsg);

                    lstMessage.SelectedIndex = lstMessage.Items.Count - 1;  //最新一条记录被选择
                    
                }

                /// <summary>
                /// 获得一个节点的值
                /// </summary>
                /// <param name="strInfo">原始字符串,查询的结果</param>
                /// <param name="strCompare">节点名称</param>
                /// <param name="maxLength">该节点值允许的最大长度</param>
                /// <returns>节点值</returns> 
                private string getImeiInfoFromString(string strInfo, string strCompare, int maxLength)
                {
                    int position1 = 0;
                    int position2 = 0;
                    string strSearch = string.Format(NODENAME, strCompare);

                    //查询IMEI的位置
                    position1 = strInfo.IndexOf(strSearch);
                    if (position1 == 0)
                    {
                        return STR_ERROR;
                    }

                    //查询BRANDC
                    position1 = position1 + strSearch.Length;

                    //查询BRAND的结束位置
                    string strEndFlag = @"'>";
                    position2 = strInfo.IndexOf(strEndFlag, position1);

                    //判断查询的结果是否有效,BRAND的长度不能大于maxLength,  也不能小于0
                    if ((position2 - position1) > maxLength || (position2 - position1)< 0)
                    {
                        return STR_ERROR;
                    }

                    // 返回查询的数据
                    return strInfo.Substring(position1, position2 - position1);
                }

                /// <summary>
                /// 保存查询IMEI后得到的结果XML文件,作为调试使用
                /// </summary>
                /// <param name="rst">获得的XML字符串</param>
                private void saveWebResponse(string rst, string strImei)
                {
                    FileStream fs = null;   //定义文件句柄
                    StreamWriter sw = null; //定义写文件流对象

                    if (rst == string.Empty)
                    {
                        printMessage("The source code is empty when saveWebResponse!");
                        return;
                    }

                    try
                    {
                        string strName = string.Format("{0}_{1}.html", strImei, DateTime.Now.ToString("yyyyMMddHHmmss")); //获得文件名
                        fs = new FileStream(strHtmlPath + strName, FileMode.Create);//创建一个文件,等待写入
                        sw = new StreamWriter(fs);
                        sw.Write(rst);       //写入获得字符串

                        printMessage("The source code has been saved when saveWebResponse!");

                    }
                    catch (Exception ex)
                    {
                        printMessage("save source code is fail when saveWebResponse!");

                    }
                    finally
                    {
                        if (sw != null) sw.Close();          //释放内存对象
                        if (fs != null) fs.Close();           //关闭文件句柄
                    }
                }


                /// <summary>
                /// 当检测到网络异常的处理
                /// 停下查询厂家或者型号的时钟,开始在拨号,并且启动等待拨号成功定时器
                /// </summary>
                private void DealnetErr()
                {
                    //停止查询定时器
                    timSearchInfo.Stop();

                    //启动再拨号
                    ReDial();

                    //启动等待成功定时器
                    timerGetIP.Start();
                }

                /// <summary>
                /// 再拨号处理
                /// </summary>
                private void ReDial()
                {
                    RASDisplay ras = new RASDisplay();                              //拨号的对象
                    uint redialState = 0;
                    printMessage("network is down,Auto to ReDail!"); //提示等待25秒,但是网络还是异常

                    if (ras.IsConnected)    // Disconnect the ADSL
                    {
                        redialState = ras.Disconnect();

                        if (redialState != 0)
                        {
                            printMessage("Disconnect Network Failed.");
                        }
                        else
                        {
                            printMessage("Disconnect Network Successful!");
                        }
                    }

                    Thread.Sleep(5000);         //等待5S
                    if (0 != ras.Connect("ADSL"))        //拨号处理,待改进
                    {
                        printMessage("Redial Error.");
                        Thread.Sleep(60000);
                    }
                    else
                    {
                        printMessage("Redial Successful!");
                    }
                }

                /// <summary>
                /// 通过ping获得网络连接状况
                /// </summary>
                /// <param name="url">ping目标地址</param>
                /// <returns></returns>
                private bool isConnect(string url)
                {
                    Ping pingSender = new Ping();  //ping发送对象
                    PingReply reply = null;
                    bool blnNetStatus = false;     //网络状态

                    //执行PING动作
                    try
                    {
                        reply = pingSender.Send(url, 100);   //100 ms 超时
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        //网络异常
                        if (reply == null || (reply != null && reply.Status != IPStatus.Success))
                        {
                            blnNetStatus = false;
                        }
                        //网络正常
                        else if (reply.Status == IPStatus.Success)
                        {
                            blnNetStatus = true;
                        }
                        //其他情况都认为是异常
                    }
                    return blnNetStatus;
                }

                /// <summary>
                /// 通过获取本地的IP地址,如果断网状态,IP地址为空或者异常
                /// </summary>
                /// <returns></returns>
                private bool isConnect()
                {
                    
                    bool blnNetStatus = true ;
                    //获取本地IP地址操作
                    string HostName = Dns.GetHostName();
                    string strIP = string.Empty;

                    //根据主角名称,获得第一块网卡的IP地址,如果多块,请只保留拨号的网卡
                    IPHostEntry MyEntry = Dns.GetHostByName(Dns.GetHostName());
                    IPAddress MyAddress = new IPAddress(MyEntry.AddressList[0].Address);
                    strIP = MyAddress.ToString();

                    //应该有2种情况可以判别是异常,一种是没有IP信息,一种是获得的IP地址值一个不可通信的169.xxx.xxx.xxx
                    if (strIP == "" || strIP.StartsWith("169") == true  )
                    {
                        blnNetStatus = false;
                    }

                    //返回连接状态
                    return blnNetStatus; 
            
                }

        #endregion




    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值