编程添加路线

我写了一个简单的实用程序,为特定的接口添加一个路由。 代码很简单:

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工作正常,我得到接口号码,但是当我跑route我得到一个错误:

无效的MASK会产生一个错误,即(DEST&MASK)!= DEST。

我认为问题是,进程启动参数不传递,因为我发送同样的错误,而不是发送routeAdd参数同时这个命令工作正常,当我在cmd中提示它。

可执行文件以pipe理员身份运行。

我试图用winapi创build它,但是它也失败了

 const string firstConnection = "someconnect"; StartProcess("rasdial", firstConnection); var interfaceIndex = GetInterfaceIndex(firstConnection); //Everything is fine var route = new MIB_IPFORWARDROW { dwForwardDest = BitConverter.ToUInt32(IPAddress.Parse("XX.XX.XX.XX").GetAddressBytes(), 0), dwForwardMask = BitConverter.ToUInt32(IPAddress.Parse("255.255.255.255").GetAddressBytes(), 0), dwForwardNextHop = BitConverter.ToUInt32(IPAddress.Parse("XXX.XXX.XXX.XXX").GetAddressBytes(), 0), dwForwardMetric1 = 99, dwForwardIfIndex = interfaceIndex }; var ipForwardEntry = RouteInterop.CreateIpForwardEntry(ref route); Console.WriteLine(ipForwardEntry); 

返回ERROR_INVALID_PARAMETER

Solutions Collecting From Web of "编程添加路线"

我知道这个问题不是很复杂,但我在互联网上没有遇到任何解释,这就是为什么我认为这个答案会有帮助,这就是为什么我写这个问题而不是删除我最初的问题。

你只需要指定更多的参数来使其工作

  var route = new MIB_IPFORWARDROW { dwForwardDest = BitConverter.ToUInt32(IPAddress.Parse("XX.XX.XX.XX").GetAddressBytes(), 0), dwForwardMask = BitConverter.ToUInt32(IPAddress.Parse("255.255.255.255").GetAddressBytes(), 0), dwForwardNextHop = BitConverter.ToUInt32(IPAddress.Parse("XXX.XXX.XXX.XXX").GetAddressBytes(), 0), dwForwardMetric1 = 99, dwForwardType = ForwardType.Indirect, dwForwardProto = ForwardProtocol.NetMGMT, dwForwardAge = 0, dwForwardIfIndex = interfaceIndex }; var ipForwardEntry = RouteInterop.CreateIpForwardEntry(ref route);