Last active
November 2, 2024 08:19
-
-
Save DartPower/1c0bd859171a40bd8ee64a889f220280 to your computer and use it in GitHub Desktop.
Windows VPN ReDial if ping to VPN's Gateway is fault.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Net.NetworkInformation; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace VPNCheckerAndReRasdial | |
{ | |
internal class Program | |
{ | |
static readonly string ipAddress = File.ReadAllText(@"cfg_ip_gateway.txt"); // "192.168.1.1"; // VPN Gateway | |
static async Task Main() | |
{ | |
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"); | |
Ping pingSender = new Ping(); | |
while (true) | |
{ | |
//Wait for some time before ping again | |
Thread.Sleep(5000); | |
try | |
{ | |
var reply = await pingSender.SendPingAsync(ipAddress); | |
for (int i = 0; i < 5; i++) | |
{ | |
Console.WriteLine("[" + DateTime.Now.ToString() + "] " + $"{reply.Buffer.Length} bytes from {reply.Address}:" + $" icmp_seq={i} status={reply.Status} time={reply.RoundtripTime}ms"); | |
} | |
if (reply.Status == 0) | |
{ | |
Console.WriteLine("[" + DateTime.Now.ToString() + "] " + "Ping successful. VPN still working..."); | |
} | |
else | |
{ | |
Trace.WriteLine("[" + DateTime.Now.ToString() + "] " + "Ping unsuccessful. Reconnecting VPN..."); | |
ProcessStartInfo rasdial = new ProcessStartInfo | |
{ | |
FileName = "rasdial", | |
Arguments = File.ReadAllText(@"cfg_line.txt") // "VPN_Interface_Name Login Password"; // ChangeMe | |
}; | |
Process.Start(rasdial); | |
} | |
} | |
catch (PingException e) | |
{ | |
Trace.WriteLine("[" + DateTime.Now.ToString() + "] " + e.Message); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment