c#检查网络是否连接互联网的方法


 

1. 调用 cmd 中的 ping 命令,分析输出信息来确定网络是否连接

 

 1 //导入命名空间
 2 using System.Net.NetworkInformation;
 3 
 4 
 5     /// <summary>
 6     /// Ping命令检测网络是否畅通
 7     /// </summary>
 8     /// <param name="url">URL地址</param>
 9     /// <returns>是否ping通</returns>
10     public static bool ChinarPing(string url)
11     {
12         Ping ping      = new Ping();
13         try
14         {
15               PingReply pr = ping.Send(url);
16             if (pr.Status == IPStatus.Success)
17             {
18                    return true;
19             }
20             else
21             {
22                   return false;
23             }    
24         }
25           
26         catch
27         {
28             isSucceed = false;
29         }
30     }                

 

 

 

 

2. 使用InternetGetConnectedState () 函数

 

 public const  int INTERNET_CONNECTION_MODEM      = 0x01; //调制解调器连接到 Internet
    public const  int INTERNET_CONNECTION_LAN        = 0x02; //局域网网卡连接到 Internet
    public const  int INTERNET_CONNECTION_PROXY      = 0x04; //代理服务器连接到 Internet
    private const int INTERNET_RAS_INSTALLED         = 0x08; //已安装 RAS
    public const  int INTERNET_CONNECTION_OFFLINE    = 0x14; //脱机模式
    public const  int INTERNET_CONNECTION_CONFIGURED = 0x40; //具有到 Internet 的有效连接,但它当前可能连接也可能不连接

 

 

 

 

 //使用DllImport需导入命名空间
 using System.Runtime.InteropServices;
 
 //导入判断网络是否连接的 .dll //判断网络状况的方法,返回值true为连接,false为未连接 
 [DllImport("wininet.dll")]
  private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
 
  /// <summary>
  /// 用于检查网络是否可以连接互联网,true表示连接成功,false表示连接失败
 /// </summary>
 /// <returns></returns>
  public static bool IsConnectInternet()
  {
     int Description = 0;
      return InternetGetConnectedState(Description, 0);
  }

/// <summary>
    /// 判断本地的连接状态
    /// </summary>
    private static bool IsConnectedInternet()
    {
        int dwFlag = new int();
        if (!InternetGetConnectedState(ref dwFlag, 0))
        {
            PrintR("当前没有联网,请您先联网后再进行操作!");
            if ((dwFlag & 0x14) == 0) return false;
            Debug.LogWarning("本地系统处于脱机模式。");
            return false;
        }
        else
        {
            if ((dwFlag & 0x01) != 0)
            {
                Print("调制解调器上网。");
                return true;
            }
            else if ((dwFlag & 0x02) != 0)
            {
                Print("网卡上网。");
                return true;
            }
            else if ((dwFlag & 0x04) != 0)
            {
                Print("代理服务器上网。");
                return true;
            }
            else if ((dwFlag & 0x40) != 0)
            {
                Print("虽然可以联网,但可能链接也可能不连接。");
                return true;
            }
        }

        return false;
    }

 

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM