0

我想使用Win32_IP4RouteTable添加路由表

代码:

ManagementClass wmiclass = new ManagementClass("Win32_IP4RouteTable");
ManagementObject route = wmiclass.CreateInstance();
route["Destination"] = "145.63.20.102";
route["NextHop"] = "172.16.213.2";
route["Mask"] = "255.255.255.255";
route["Metric1"] = 20;
route.Put();//or route.Put(new PutOptions() { Type = 
PutType.UpdateOrCreate });

我在Put()方法上遇到异常:

`System.Management.Management:Invalid parameter`

如何使用 Put 方法创建新项目

4

2 回答 2

0

您可以为此使用ORMi库。它是 WMI 的轻量级 ORM。

1)定义你的班级:

[WMIClass("Win32_IP4RouteTable")]
public class RouteTable
{
    public string Destination{ get; set; }
    public string NextHop{ get; set; }
    public string Mask{ get; set; }
    public string Metric1{ get; set; }
}

注意:似乎可能需要一些属性,因此您会得到“无效参数”。如果是这种情况,那么只需将所需的类添加到RouteTable类中。

2)使用库:

WMIHelper helper = new WMIHelper("root\\CimV2");

RouteTable route = new RouteTable
{
    Destination = "145.63.20.102",
    NextHop = "172.16.213.2",
    Mask = "255.255.255.255",
    Metric1 = "20"
};

helper.AddInstance(route);

就是这样。

于 2018-06-07T19:33:36.733 回答
0

像这样,谢谢@Jimi `

    [DllImport("Iphlpapi.dll")]
    [return: MarshalAs(UnmanagedType.U4)]
    public static extern int CreateIpForwardEntry(ref MIB_IPFORWARDROW pRoute);

   public static int createIpForwardEntry(UInt32 destIPAddress, UInt32 destMask, UInt32 nextHopIPAddress, UInt32 ifIndex, int metric)
    {
        MIB_IPFORWARDROW mifr = new MIB_IPFORWARDROW();
        mifr.dwForwardDest = destIPAddress;
        mifr.dwForwardMask = destMask;
        mifr.dwForwardNextHop = nextHopIPAddress;
        mifr.dwForwardIfIndex = ifIndex;
        mifr.dwForwardPolicy = Convert.ToUInt32(0);
        mifr.dwForwardType = Convert.ToUInt32(3);
        mifr.dwForwardProto = Convert.ToUInt32(3);
        mifr.dwForwardAge = Convert.ToUInt32(0);
        mifr.dwForwardNextHopAS = Convert.ToUInt32(0);
        mifr.dwForwardMetric1 = metric;
        mifr.dwForwardMetric2 = -1;
        mifr.dwForwardMetric3 = -1;
        mifr.dwForwardMetric4 = -1;
        mifr.dwForwardMetric5 = -1;
        return CreateIpForwardEntry(ref mifr);
    }

`

于 2018-04-23T10:27:28.763 回答