判斷是否能連線網際網路

网络来者發表於2024-08-31

static bool CheckInternetConnection()
{
try
{
Ping ping = new Ping();
PingReply reply = ping.Send("8.8.8.8");
return reply.Status == IPStatus.Success;
}
catch (Exception)
{
return false;
}
}


static bool CheckInternetConnectionByWebRequest()
{
try
{
WebRequest request = WebRequest.Create("https://www.baidu.com/");
using (WebResponse response = request.GetResponse())
{
return true;
}
}
catch
{
return false;
}
}



static void Main()
{
bool isConnected = CheckInternetConnection();
if (isConnected)
{
Console.WriteLine("有網際網路連線。");
}
else
{
Console.WriteLine("沒有網際網路連線。");
}

Console.ReadKey();
}

相關文章