Skip to content

Instantly share code, notes, and snippets.

@DartPower
Last active April 2, 2023 14:11
Show Gist options
  • Select an option

  • Save DartPower/fef93da818728039990ae878900725e6 to your computer and use it in GitHub Desktop.

Select an option

Save DartPower/fef93da818728039990ae878900725e6 to your computer and use it in GitHub Desktop.
Network Interface restarter (If connection fail)
using System;
using System.Globalization;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace NetworkRestarter
{
internal class Program
{
public static string interfaceName = File.ReadAllText(@".\AdapterName.txt");
static void EnableAdapter(string interfaceName)
{
Process.Start(new ProcessStartInfo("cmd", "/c netsh interface set interface \"" + interfaceName + "\" enable")
{
Verb = "runas"
});
}
static void DisableAdapter(string interfaceName)
{
Process.Start(new ProcessStartInfo("cmd", "/c netsh interface set interface \"" + interfaceName + "\" disable")
{
Verb = "runas"
});
}
public static bool CheckForInternetConnection(int timeoutMs = 10000, string url = null)
{
try
{
url ??= CultureInfo.InstalledUICulture switch
{
{ Name: var n } when n.StartsWith("ru") => // Russia
"http://www.ya.ru",
{ Name: var n } when n.StartsWith("fa") => // Iran
"http://www.aparat.com",
{ Name: var n } when n.StartsWith("zh") => // China
"http://www.baidu.com",
_ =>
"http://www.gstatic.com/generate_204",
};
var request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.Timeout = timeoutMs;
using (var response = (HttpWebResponse)request.GetResponse())
return true;
}
catch
{
return false;
}
}
[STAThread]
static void Main(string[] args)
{
Marshal.PrelinkAll(typeof(Program));
Trace.AutoFlush = true;
Trace.Listeners.Clear();
Trace.Listeners.Add(new ConsoleTraceListener());
Trace.Listeners.Add(new TextWriterTraceListener(System.IO.Path.GetFileNameWithoutExtension(typeof(Program).Assembly.GetName().Name) + ".log"));
Trace.WriteLine("[" + DateTime.Now.ToString() + "] " + "Started");
Task.Run(() =>
{
while (true)
{
Thread.Sleep(60000);
Trace.WriteLine("[" + DateTime.Now.ToString() + "] " + "Checking internet connection");
if (CheckForInternetConnection(10000, "http://www.ya.ru") == false)
{
Thread.Sleep(5000);
Trace.WriteLine("[" + DateTime.Now.ToString() + "] " + "Disabling Network Adapter...");
DisableAdapter(interfaceName);
Thread.Sleep(5000);
Trace.WriteLine("[" + DateTime.Now.ToString() + "] " + "Enabling Network Adapter...");
EnableAdapter(interfaceName);
Thread.Sleep(5000);
}
else
{
}
}
});
ConsoleKeyInfo input;
do
{
input = Console.ReadKey();
} while (input.Key != ConsoleKey.Escape);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment