libnetfilter_acct  1.0.3
nfacct-add.c
1 /* This example is in the public domain. */
2 #include <stdlib.h>
3 #include <time.h>
4 #include <string.h>
5 #include <libmnl/libmnl.h>
6 #include <libnetfilter_acct/libnetfilter_acct.h>
7 
8 int main(int argc, char *argv[])
9 {
10  struct mnl_socket *nl;
11  char buf[MNL_SOCKET_BUFFER_SIZE];
12  struct nlmsghdr *nlh;
13  uint32_t portid, seq;
14  struct nfacct *nfacct;
15  int ret;
16 
17  if (argc != 2) {
18  fprintf(stderr, "Usage: %s [name]\n", argv[0]);
19  exit(EXIT_FAILURE);
20  }
21 
22  nfacct = nfacct_alloc();
23  if (nfacct == NULL) {
24  perror("OOM");
25  exit(EXIT_FAILURE);
26  }
27 
28  nfacct_attr_set(nfacct, NFACCT_ATTR_NAME, argv[1]);
29 
30  seq = time(NULL);
31  nlh = nfacct_nlmsg_build_hdr(buf, NFNL_MSG_ACCT_NEW,
32  NLM_F_CREATE | NLM_F_ACK, seq);
33  nfacct_nlmsg_build_payload(nlh, nfacct);
34 
35  nfacct_free(nfacct);
36 
37  nl = mnl_socket_open(NETLINK_NETFILTER);
38  if (nl == NULL) {
39  perror("mnl_socket_open");
40  exit(EXIT_FAILURE);
41  }
42 
43  if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
44  perror("mnl_socket_bind");
45  exit(EXIT_FAILURE);
46  }
47  portid = mnl_socket_get_portid(nl);
48 
49  if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0) {
50  perror("mnl_socket_send");
51  exit(EXIT_FAILURE);
52  }
53 
54  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
55  while (ret > 0) {
56  ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
57  if (ret <= 0)
58  break;
59  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
60  }
61  if (ret == -1) {
62  perror("error");
63  exit(EXIT_FAILURE);
64  }
65  mnl_socket_close(nl);
66 
67  return EXIT_SUCCESS;
68 }
void nfacct_nlmsg_build_payload(struct nlmsghdr *nlh, struct nfacct *nfacct)
void nfacct_attr_set(struct nfacct *nfacct, enum nfacct_attr_type type, const void *data)
void nfacct_free(struct nfacct *nfacct)
struct nlmsghdr * nfacct_nlmsg_build_hdr(char *buf, uint8_t cmd, uint16_t flags, uint32_t seq)
struct nfacct * nfacct_alloc(void)