【问题标题】:How use WMI add route table with C#C#如何使用WMI添加路由表
【发布时间】:2018-04-15 08:50:39
【问题描述】:

我想用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 方法创建新项目

【问题讨论】:

  • 我必须制作一个执行此类任务的 c++ 库。如果我没记错的话,Win32_IP4RouteTable 用于读取这些设置,而不是修改它们。当时,我很确定我为此使用了CreateIpForwardEntry。它是IPHelper Functions 的一部分。不过,我不确定 c# 的实现。试试这个 SO 问题:Programmatically add route
  • 嗨,我已经解决了这个问题,使用 IPHelper,谢谢!
  • 我很高兴它有帮助。也许,发布您的解决方案作为答案,它可能对其他人有用。
  • 再次感谢您,我已经发布了我的解决方案

标签: c# wmi routetable


【解决方案1】:

喜欢这个,谢谢@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);
    }

`

【讨论】:

    【解决方案2】:

    您可以为此使用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);
    

    就是这样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2021-01-22
      • 2016-03-30
      • 2022-01-15
      • 2020-11-08
      • 1970-01-01
      相关资源
      最近更新 更多