16 #include <netinet/in.h>
17 #include <netinet/ip.h>
18 #include <netinet/tcp.h>
19 #include <arpa/inet.h>
20 #include <sys/types.h>
21 #include <sys/socket.h>
24 #include <linux/netfilter.h>
25 #include <linux/netfilter/nfnetlink.h>
26 #include <linux/netfilter/nf_tables.h>
28 #include <libmnl/libmnl.h>
29 #include <libnftnl/set.h>
31 static struct nftnl_set *setup_set(uint8_t family,
const char *table,
34 struct nftnl_set *s = NULL;
36 s = nftnl_set_alloc();
42 nftnl_set_set_str(s, NFTNL_SET_TABLE, table);
43 nftnl_set_set_str(s, NFTNL_SET_NAME, name);
44 nftnl_set_set_u32(s, NFTNL_SET_FAMILY, family);
45 nftnl_set_set_u32(s, NFTNL_SET_KEY_LEN, 2);
46 nftnl_set_set_u32(s, NFTNL_SET_ID, 1);
47 nftnl_set_set_u32(s, NFTNL_SET_FLAGS, NFT_SET_CONSTANT);
52 static void nftnl_mnl_batch_put(
char *buf, uint16_t type, uint32_t seq)
57 nlh = mnl_nlmsg_put_header(buf);
58 nlh->nlmsg_type = type;
59 nlh->nlmsg_flags = NLM_F_REQUEST;
62 nfg = mnl_nlmsg_put_extra_header(nlh,
sizeof(*nfg));
63 nfg->nfgen_family = AF_INET;
64 nfg->version = NFNETLINK_V0;
65 nfg->res_id = NFNL_SUBSYS_NFTABLES;
68 int main(
int argc,
char *argv[])
70 struct mnl_socket *nl;
73 struct mnl_nlmsg_batch *batch;
75 char buf[MNL_SOCKET_BUFFER_SIZE];
76 uint32_t seq = time(NULL);
80 fprintf(stderr,
"Usage: %s <family> <table> <setname>\n", argv[0]);
84 if (strcmp(argv[1],
"ip") == 0)
85 family = NFPROTO_IPV4;
86 else if (strcmp(argv[1],
"ip6") == 0)
87 family = NFPROTO_IPV6;
88 else if (strcmp(argv[1],
"bridge") == 0)
89 family = NFPROTO_BRIDGE;
90 else if (strcmp(argv[1],
"arp") == 0)
93 fprintf(stderr,
"Unknown family: ip, ip6, bridge, arp\n");
97 s = setup_set(family, argv[2], argv[3]);
99 nl = mnl_socket_open(NETLINK_NETFILTER);
101 perror(
"mnl_socket_open");
105 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
106 perror(
"mnl_socket_bind");
110 batch = mnl_nlmsg_batch_start(buf,
sizeof(buf));
112 nftnl_mnl_batch_put(mnl_nlmsg_batch_current(batch),
113 NFNL_MSG_BATCH_BEGIN, seq++);
114 mnl_nlmsg_batch_next(batch);
116 nlh = nftnl_set_nlmsg_build_hdr(mnl_nlmsg_batch_current(batch),
117 NFT_MSG_NEWSET, family,
118 NLM_F_CREATE|NLM_F_ACK, seq++);
120 nftnl_set_nlmsg_build_payload(nlh, s);
122 mnl_nlmsg_batch_next(batch);
124 nftnl_mnl_batch_put(mnl_nlmsg_batch_current(batch), NFNL_MSG_BATCH_END,
126 mnl_nlmsg_batch_next(batch);
128 ret = mnl_socket_sendto(nl, mnl_nlmsg_batch_head(batch),
129 mnl_nlmsg_batch_size(batch));
131 perror(
"mnl_socket_sendto");
135 mnl_nlmsg_batch_stop(batch);
137 ret = mnl_socket_recvfrom(nl, buf,
sizeof(buf));
139 perror(
"mnl_socket_recvfrom");
143 ret = mnl_cb_run(buf, ret, 0, mnl_socket_get_portid(nl), NULL, NULL);
145 perror(
"mnl_cb_run");
149 mnl_socket_close(nl);