a C# program that checks if connected to network by piging a specific website (g
ID: 3913880 • Letter: A
Question
a C# program that checks if connected to network by piging a specific website (google.com), if the server replies that means it's connected to the internet and if it says "request timed out" or isn't pinging that means it is not connected to the internet. In the case of not connected to the internet, the program should close an external running program, for example "Matlab.exe" and reopen it in 1 min and then check for internet again. In the case of it is connected to internet, it should keep checking every 10 secs.
Explanation / Answer
Hi,
Below is the console program which does the job explained. it keeps running until you enter 'q' to stop the application. Here I have used timers to keep track of successful and unsuccessful pings. I have tested and it works fine. I have kept the program as simple as possible.
If you still have any doubt or problem please contact me.
If it solves your problem please give me thumbs up. Thanks.
using System;
using System.Diagnostics;
using System.Linq;
using System.Timers;
namespace Chegg_Network_Ping
{
class Program
{
static System.Timers.Timer successTimer = new System.Timers.Timer();
static System.Timers.Timer unsuccessTimer = new System.Timers.Timer();
static void Main(string[] args)
{
successTimer.Elapsed += new ElapsedEventHandler(OnSuccessEvent);
unsuccessTimer.Elapsed += new ElapsedEventHandler(OnUnsuccessEvent);
Check();
Console.WriteLine("Press 'q' to quit the application.");
while (Console.Read() != 'q') ;
}
private static void Check()
{
if (Ping())
{
unsuccessTimer.Enabled = false;
if (!successTimer.Enabled)
{
successTimer.Interval = 10000;
successTimer.Enabled = true;
}
}
else
{
killMatlabProcess();
successTimer.Enabled = false;
if (!unsuccessTimer.Enabled)
{
unsuccessTimer.Interval = 60000;
unsuccessTimer.Enabled = true;
}
}
}
private static void killProcess()
{
var matlabProcesses = Process.GetProcesses().
Where(pr => pr.ProcessName == "Matlab");
foreach (var process in matlabProcesses)
{
process.Kill();
}
}
private static void OnSuccessEvent(object source, ElapsedEventArgs e)
{
Check();
}
private static void OnUnsuccessEvent(object source, ElapsedEventArgs e)
{
Process.Start("Matlab.exe");
Check();
}
private static bool Ping()
{
var ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply result;
try { result = ping.Send("www.google.com"); }
catch
{
return false;
}
return result.Status == System.Net.NetworkInformation.IPStatus.Success;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.