以编程方式添加路线

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

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。

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

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

我正在尝试用winapi创建它,但它也失败了

 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

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

您应该指定更多参数以使其工作

  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);