Ale*_*kiy 5 .net c# windows routing cmd
我编写了一个简单的实用程序,为特定接口添加了路由。代码很简单:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
退货 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);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2569 次 |
最近记录: |