11 #include <netinet/in.h>
13 #include <linux/netfilter.h>
14 #include <linux/netfilter/nf_tables.h>
16 #include <libmnl/libmnl.h>
17 #include <libnftnl/rule.h>
19 static int table_cb(
const struct nlmsghdr *nlh,
void *data)
23 uint32_t *type = data;
25 t = nftnl_rule_alloc();
31 if (nftnl_rule_nlmsg_parse(nlh, t) < 0) {
32 perror(
"nftnl_rule_nlmsg_parse");
36 nftnl_rule_snprintf(buf,
sizeof(buf), t, *type, 0);
45 static struct nftnl_rule *setup_rule(uint8_t family,
const char *table,
46 const char *chain,
const char *handle)
51 r = nftnl_rule_alloc();
56 nftnl_rule_set_str(r, NFTNL_RULE_TABLE, table);
58 nftnl_rule_set_str(r, NFTNL_RULE_CHAIN, chain);
60 nftnl_rule_set_u32(r, NFTNL_RULE_FAMILY, family);
63 handle_num = atoll(handle);
64 nftnl_rule_set_u64(r, NFTNL_RULE_POSITION, handle_num);
70 int main(
int argc,
char *argv[])
72 struct mnl_socket *nl;
73 char buf[MNL_SOCKET_BUFFER_SIZE];
75 uint32_t portid, seq, type = NFTNL_OUTPUT_DEFAULT;
76 const char *table = NULL, *chain = NULL;
80 if (argc < 2 || argc > 5) {
81 fprintf(stderr,
"Usage: %s <family> [<table> <chain>]\n",
86 if (strcmp(argv[1],
"ip") == 0)
87 family = NFPROTO_IPV4;
88 else if (strcmp(argv[1],
"ip6") == 0)
89 family = NFPROTO_IPV6;
90 else if (strcmp(argv[1],
"inet") == 0)
91 family = NFPROTO_INET;
92 else if (strcmp(argv[1],
"bridge") == 0)
93 family = NFPROTO_BRIDGE;
94 else if (strcmp(argv[1],
"arp") == 0)
96 else if (strcmp(argv[1],
"unspec") == 0)
97 family = NFPROTO_UNSPEC;
99 fprintf(stderr,
"Unknown family: ip, ip6, inet, bridge, arp, unspec\n");
110 nlh = nftnl_nlmsg_build_hdr(buf, NFT_MSG_GETRULE, family,
113 r = setup_rule(family, table, chain, NULL);
115 perror(
"setup_rule");
118 nftnl_rule_nlmsg_build_payload(nlh, r);
120 nl = mnl_socket_open(NETLINK_NETFILTER);
122 perror(
"mnl_socket_open");
126 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
127 perror(
"mnl_socket_bind");
130 portid = mnl_socket_get_portid(nl);
132 if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
133 perror(
"mnl_socket_send");
137 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
139 ret = mnl_cb_run(buf, ret, seq, portid, table_cb, &type);
142 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
148 mnl_socket_close(nl);