通过API Windows防火墙Delphi添加阻止IP地址的规则

时间:2014-08-13 08:14:45

标签: windows delphi firewall

下午好。 没有人在Delphi中添加Windows防火墙规则? 我需要限制来自特定IP地址的传入和传出连接。 这段代码在启动时抛出了一个错误信息:

  

00033E74模块Project1.exe中的异常EVariantInvalidOpError。变种操作无效。

有没有人有什么错误?

procedure TForm1.FormCreate(Sender: TObject);
Const
 NET_FW_IP_PROTOCOL_TCP = 6;
 NET_FW_IP_PROTOCOL_UDP = 17;
 NET_FW_ACTION_ALLOW = 1;
 NET_FW_RULE_DIR_in = 1;

var
 CurrentProfiles : OleVariant;
 fwPolicy2       : OleVariant;
 RulesObject     : OleVariant;
 NewRule         : OleVariant;
 txtAddress      : OleVariant;
 NET_FW_ACTION_  : OleVariant;
 NET_FW_RULE_DIRECTION_: OleVariant;

begin
  // Create the FwPolicy2 object.
  fwPolicy2   := CreateOleObject('HNetCfg.FwPolicy2');
  RulesObject := fwPolicy2.Rules;
  CurrentProfiles := fwPolicy2.CurrentProfileTypes;
   txtaddress.text:='192.168.1.33';
  //Create a Rule Object.
  NewRule := CreateOleObject('HNetCfg.FWRule');

        newrule.Name:= 'BrutalNT: IP Access Block ' + txtAddress.Text;
        newrule.Description := 'Block Incoming Connections from IP Address.';
        newrule.Action := 1;
        newrule.Direction := NET_FW_RULE_DIR_IN;
        newrule.Enabled := true;
        newrule.InterfaceTypes := 'All';
        newrule.RemoteAddresses := txtAddress.Text;

  //Add a new rule
  RulesObject.Add(NewRule);
end;

1 个答案:

答案 0 :(得分:4)

您正在使用txtAddress : OleVariant但没有任何结构。所以你不能使用txtAddress.text这样的东西,因为没有任何地方可以映射它。

只需将类型更改为stringtxtAddress就不需要OleVariant类型。

procedure TForm1.FormCreate(Sender: TObject);
Const
 NET_FW_IP_PROTOCOL_TCP = 6;
 NET_FW_IP_PROTOCOL_UDP = 17;
 NET_FW_ACTION_BLOCK = 0;
 NET_FW_ACTION_ALLOW = 1;
 NET_FW_RULE_DIR_IN = 1;

var
 CurrentProfiles : OleVariant;
 fwPolicy2       : OleVariant;
 RulesObject     : OleVariant;
 NewRule         : OleVariant;
 txtAddress      : string; // OleVariant;

begin
  // Create the FwPolicy2 object.
  fwPolicy2   := CreateOleObject('HNetCfg.FwPolicy2');
  RulesObject := fwPolicy2.Rules;
  CurrentProfiles := fwPolicy2.CurrentProfileTypes;
  txtaddress{.text}:='192.168.1.33';
  //Create a Rule Object.
  NewRule := CreateOleObject('HNetCfg.FWRule');

  Newrule.Name := 'BrutalNT: IP Access Block ' + txtAddress{.Text};
  Newrule.Description := 'Block Incoming Connections from IP Address.';
  Newrule.Action := NET_FW_ACTION_BLOCK{1};
  Newrule.Direction := NET_FW_RULE_DIR_IN;
  Newrule.Enabled := true;
  Newrule.InterfaceTypes := 'All';
  Newrule.RemoteAddresses := txtAddress{.Text};

  //Add a new rule
  RulesObject.Add(NewRule);
end;

BTW 如果你想阻止,你必须设置NewRule.Action := 0;(NET_FW_ACTION_BLOCK)