how to use :
# man 3 libnftables
const char *nft_ctx_get_output_buffer(struct nft_ctx *ctx);
I want save nftables rules (without print on console). but nft_run_cmd_from_buffer
immediately print rules on console .
this is my example code :
#include <stdlib.h>
#include <nftables/libnftables.h>
int main(void)
{
struct nft_ctx *ctx;
int err;
ctx = nft_ctx_new(0);
if (!ctx) {
perror("cannot allocate nft context");
return EXIT_FAILURE;
}
nft_ctx_output_set_flags(ctx, NFT_CTX_OUTPUT_HANDLE | NFT_CTX_OUTPUT_JSON);
const char* output = nft_ctx_get_output_buffer(ctx);
err = nft_run_cmd_from_buffer(ctx, "list ruleset");
if (err < 0)
fprintf(stderr, "failed to run nftables command\n");
nft_ctx_free(ctx);
printf ("-----------------------------------------------------\n");
printf(">> %s\n",output);
return EXIT_SUCCESS;
}
Thank you , finally fixed the problem :
According to manual page :
At the very basic level, one has to allocate a new object of type struct nft_ctx using nft_ctx_new() function, then pass commands via nft_run_cmd_from_buffer() or nft_run_cmd_from_filename() functions. By default, any output is written to stdout (or stderr for error messages). These file pointers may be changed using nft_ctx_set_output() and nft_ctx_set_error() functions. On top of that, it is possible to have any output buffered by the library for later retrieval as a static buffer. See nft_ctx_buffer_output() and nft_ctx_buffer_error() functions for details.
so code is :
#include <stdio.h>
#include <stdlib.h>
#include <nftables/libnftables.h>
int main() {
struct nft_ctx *ctx;
int err;
const char *output;
ctx = nft_ctx_new(0);
if (!ctx) {
perror("cannot allocate nft context");
return EXIT_FAILURE;
}
nft_ctx_output_set_flags(ctx, NFT_CTX_OUTPUT_HANDLE | NFT_CTX_OUTPUT_JSON);
nft_ctx_buffer_output(ctx);
err = nft_run_cmd_from_buffer(ctx, "list ruleset");
if (err < 0)
fprintf(stderr, "failed to run nftables command\n");
output = nft_ctx_get_output_buffer(ctx);
if (output != NULL) {
printf("Output: %s\n", output);
}
nft_ctx_free(ctx);
return EXIT_SUCCESS;
}