码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2020-06-28 15:05:45      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:gre   cte   utf8   new   byte   cal   stat   internet   tco   

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;
        }
    }

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

标签:gre   cte   utf8   new   byte   cal   stat   internet   tco   

原文地址:https://www.cnblogs.com/midhuhu/p/13202729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!