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

2021-01-03 22:29

阅读:692

标签: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);

    }
    /// 
    ??????? /// 是否连接到服务器,true表示连接成功,false表示连接失败
    ??????? /// 
    ??????? /// 输入参数,表示IP地址或域名
    ??????? /// 
    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


评论


亲,登录后才可以留言!