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