lundi 13 avril 2015

Programmicaly add route

I write a simple utility that adds a route for specific interface. Code is very simple:



using System;
using System.Diagnostics;
using System.Net.NetworkInformation;
using System.Text;

class Program
{
static void Main(string[] args)
{
const string firstConnection = "xxxx.yyyyy";
const string routeAddMask = "route add XX.XX.XX.XX mask 255.255.255.255 XXX.XXX.XXX.XXX METRIC 99 IF {0}";
StartProcess("rasdial", firstConnection);
var interfaceId = GetInterfaceId(firstConnection);
string routeAdd = string.Format(routeAddMask, interfaceId);
StartProcess("route", routeAdd);
}

private static int GetInterfaceId(string name)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
var adapter = Array.Find(adapters, ni => ni.Name == name);
var props = adapter.GetIPProperties().GetIPv4Properties();
return props.Index;
}

private static void StartProcess(string name, string args)
{
var process = new Process
{
StartInfo = new ProcessStartInfo(name, args)
{
UseShellExecute = false,
RedirectStandardOutput = true,
StandardOutputEncoding = Encoding.ASCII
}
};
process.Start();
while (!process.HasExited)
{
Console.WriteLine(process.StandardOutput.ReadToEnd());
}
process.WaitForExit();
Console.WriteLine("Process {0} finished, exit code = {1}", name, process.ExitCode);
}
}


rasdial works fine and I get interface number, but when I'm running route I get an error:



Invalid MASK generates an error, that is when (DEST & MASK) != DEST.



I think problem is that process start args are not passed because I get the same error while sending null instead of routeAdd parameter meanwhile this command works fine when i'm prompting it in cmd.


Executable is running as Administrator.


Aucun commentaire:

Enregistrer un commentaire