C#检测网络连接情况代码

public void Check()
{
while (true)
{
Control.CheckForIllegalCrossThreadCalls = false;
bool isConnectInternet = InternetGetConnectedState(0, 0);
if (isConnectInternet)
{
button1.Text = "网络联通";
button1.Image = global::NetCheck.Properties.Resources.网络;
}
else
{
button1.Text = "网络故障";
button1.Image = global::NetCheck.Properties.Resources.网络故障;
}
bool b = PingIpOrDomainName("192.168.0.11");
if (b)
{
button1.Text = "已连通局域网络";
button1.Image = global::NetCheck.Properties.Resources.网络;
}
else
{
button1.Text = "没有连通局域网络";
button1.Image = global::NetCheck.Properties.Resources.网络故障;
}
Thread.Sleep(300);
}

    }


    [DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(int Description, int ReservedValue);

///


        /// 检查网络是否链接
        ///

        ///
        public static bool IsConnectInternet()
{
return InternetGetConnectedState(0, 0);

    }
    /// <summary>
            /// 是否连接到服务器,true表示连接成功,false表示连接失败
            /// </summary>
            /// <param name="strIpOrDName">输入参数,表示IP地址或域名</param>
            /// <returns></returns>
    public static bool PingIpOrDomainName(string strIpOrDName)
    {
        try
        {
            Ping objPingSender = new Ping();
            PingOptions objPinOptions = new PingOptions();
            objPinOptions.DontFragment = true;
            string data = "";
            byte[] buffer = Encoding.UTF8.GetBytes(data);
            int intTimeout = 120;
            PingReply objPinReply = objPingSender.Send(strIpOrDName, intTimeout, buffer, objPinOptions);
            string strInfo = objPinReply.Status.ToString();
            // Console.WriteLine(strInfo);
            if (strInfo == "Success")
            {

                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

猜你喜欢

转载自www.cnblogs.com/midhuhu/p/13202729.html
今日推荐