Search code examples
delphiwindows-firewallwindows-firewall-api

Delphi check if port is not blocked by firewall


I'm trying to write a function that can determine if a port is blocked by firewall rules, so far I found something but it doesn't seems to work... the bAllowed and bRestricted variables remain always set to false.

function IsTCPPortAllowed(p_nPort: Integer; p_sAddress: string): Boolean;
var
  bAllowed, bRestricted: Boolean;
  oFwMgr               : OLEVariant;
  oResult              : HRESULT;
begin
  bAllowed    := False;
  bRestricted := False;
  CoInitialize(nil);
  try
    try
      oFwMgr  := CreateOLEObject('HNetCfg.FwMgr');
      oResult := oFwMgr.IsPortAllowed('', NET_FW_IP_VERSION_V4, p_nPort, p_sAddress, NET_FW_IP_PROTOCOL_TCP, bAllowed, bRestricted);
    except
    end;
  finally
    oFwMgr       := VarNull;
    CoUninitialize;
  end;

  if oResult = S_OK then
    Result := bAllowed and not bRestricted;
end;

Am I missing something here, or maybe there is another(better) way to find if a port is blocked by firewall?

Thanks in advance!


Solution

  • I finally managed to make it work, I had to use OleVariant type for bAllowed and bRestricted variables, also I removed the try ... except block and checked the return status of IsPortAllowed as @mjn sugested.

    Here is the updated version which works:

    function IsTCPPortAllowed(p_nPort: Integer; p_sAddress: string): Boolean;
    var
      bAllowed, bRestricted: OleVariant;
      oFwMgr               : OleVariant;
      oResult              : HRESULT;
    begin
      bAllowed    := False;
      bRestricted := False;
      Result      := False;
    
      CoInitialize(nil);
      try
        oFwMgr  := CreateOLEObject('HNetCfg.FwMgr');
        oResult := oFwMgr.IsPortAllowed('', NET_FW_IP_VERSION_V4, p_nPort, p_sAddress, NET_FW_IP_PROTOCOL_TCP, bAllowed, bRestricted);
        if oResult = S_OK then
          Result := bAllowed and not bRestricted;
      finally
        oFwMgr    := VarNull;
        CoUninitialize;
      end;
    end;