* Re: libnftables way of deleting a rule
2024-07-31 12:41 libnftables way of deleting a rule Arne Zachlod
@ 2024-08-01 18:01 ` Florian Westphal
0 siblings, 0 replies; 2+ messages in thread
From: Florian Westphal @ 2024-08-01 18:01 UTC (permalink / raw)
To: Arne Zachlod; +Cc: netfilter
Arne Zachlod <arne@nerdkeller.org> wrote:
> I'm porting a program (written in C) that currently uses iptables to
> nftables, trying to not change a lot of the internal concept of said
> program.
> The program currently uses execute() calls and calls iptables directly via
> these. I wanted to at least use libnftables, and everything seems to works
> quite well, I just have a problem with deleting rules.
> I read through the code of libnftables, but I couldn't find a way to get the
> handle of a rule I added. In iptables, this is no problem, you just give the
> rule again to delete it. In libnftables though I need the handle. Currently,
> I'm looking into libnftables-json, but I would prefer not to use it just to
> get the handles. Is there a better way of deleting a rule than parsing the
> JSON for them? Maybe even with libnftables directly?
Depends, if you can remember which rule has which handle assigned then
this would work, modified add example:
+++ a/examples/nft-buffer.c
+++ b/examples/nft-buffer.c
@@ -11,6 +11,8 @@ const char ruleset[] =
int main(void)
{
struct nft_ctx *ctx;
+ char buf[8192];
+ FILE *fp;
int err;
ctx = nft_ctx_new(0);
@@ -19,16 +21,20 @@ int main(void)
return EXIT_FAILURE;
}
+ nft_ctx_output_set_flags(ctx, NFT_CTX_OUTPUT_ECHO | NFT_CTX_OUTPUT_HANDLE);
+
+ buf[0] = 0;
+ fp = fmemopen(buf, sizeof(buf), "w+");
+ nft_ctx_set_output(ctx, fp);
+
/* create ruleset: all commands in the buffer are atomically applied */
err = nft_run_cmd_from_buffer(ctx, ruleset);
if (err < 0)
fprintf(stderr, "failed to run nftables command\n");
- err = nft_run_cmd_from_buffer(ctx, "list ruleset");
- if (err < 0)
- fprintf(stderr, "failed to run nftables command\n");
-
nft_ctx_free(ctx);
+ fclose(fp);
+ fprintf(stderr, "res is %s\n", buf);
return EXIT_SUCCESS;
}
NFT_CTX_OUTPUT_ECHO makes kernel dump the just-added-rule(s) back and
NFT_CTX_OUTPUT_HANDLE tells nft to postfix each line with '# handle %u'.
^ permalink raw reply [flat|nested] 2+ messages in thread