15#include <netinet/in.h>
17#include <linux/netfilter.h>
18#include <linux/netfilter/nf_tables.h>
20#include <libmnl/libmnl.h>
21#include <libnftnl/rule.h>
23static int table_cb(
const struct nlmsghdr *nlh,
void *data)
27 uint32_t *type = data;
29 t = nftnl_rule_alloc();
35 if (nftnl_rule_nlmsg_parse(nlh, t) < 0) {
36 perror(
"nftnl_rule_nlmsg_parse");
40 nftnl_rule_snprintf(buf,
sizeof(buf), t, *type, 0);
49static struct nftnl_rule *setup_rule(uint8_t family,
const char *table,
50 const char *chain,
const char *handle)
55 r = nftnl_rule_alloc();
60 nftnl_rule_set_str(r, NFTNL_RULE_TABLE, table);
62 nftnl_rule_set_str(r, NFTNL_RULE_CHAIN, chain);
64 nftnl_rule_set_u32(r, NFTNL_RULE_FAMILY, family);
67 handle_num = atoll(handle);
68 nftnl_rule_set_u64(r, NFTNL_RULE_POSITION, handle_num);
74int main(
int argc,
char *argv[])
76 struct mnl_socket *nl;
77 char buf[MNL_SOCKET_BUFFER_SIZE];
79 uint32_t portid, seq, type = NFTNL_OUTPUT_DEFAULT;
80 const char *table = NULL, *chain = NULL;
84 if (argc < 2 || argc > 5) {
85 fprintf(stderr,
"Usage: %s <family> [<table> <chain>]\n",
90 if (strcmp(argv[1],
"ip") == 0)
91 family = NFPROTO_IPV4;
92 else if (strcmp(argv[1],
"ip6") == 0)
93 family = NFPROTO_IPV6;
94 else if (strcmp(argv[1],
"inet") == 0)
95 family = NFPROTO_INET;
96 else if (strcmp(argv[1],
"bridge") == 0)
97 family = NFPROTO_BRIDGE;
98 else if (strcmp(argv[1],
"arp") == 0)
100 else if (strcmp(argv[1],
"unspec") == 0)
101 family = NFPROTO_UNSPEC;
103 fprintf(stderr,
"Unknown family: ip, ip6, inet, bridge, arp, unspec\n");
114 nlh = nftnl_nlmsg_build_hdr(buf, NFT_MSG_GETRULE, family,
117 r = setup_rule(family, table, chain, NULL);
119 perror(
"setup_rule");
122 nftnl_rule_nlmsg_build_payload(nlh, r);
124 nl = mnl_socket_open(NETLINK_NETFILTER);
126 perror(
"mnl_socket_open");
130 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
131 perror(
"mnl_socket_bind");
134 portid = mnl_socket_get_portid(nl);
136 if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
137 perror(
"mnl_socket_send");
141 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
143 ret = mnl_cb_run(buf, ret, seq, portid, table_cb, &type);
146 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
152 mnl_socket_close(nl);