libnetfilter_conntrack  1.0.6
nfct-mnl-del.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <time.h>
5 #include <arpa/inet.h>
6 
7 #include <libmnl/libmnl.h>
8 #include <libnetfilter_conntrack/libnetfilter_conntrack.h>
9 
10 #include <linux/netfilter/nf_conntrack_tcp.h>
11 
12 int main(void)
13 {
14  struct mnl_socket *nl;
15  struct nlmsghdr *nlh;
16  struct nfgenmsg *nfh;
17  char buf[MNL_SOCKET_BUFFER_SIZE];
18  unsigned int seq, portid;
19  struct nf_conntrack *ct;
20  int ret;
21 
22  nl = mnl_socket_open(NETLINK_NETFILTER);
23  if (nl == NULL) {
24  perror("mnl_socket_open");
25  exit(EXIT_FAILURE);
26  }
27 
28  if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
29  perror("mnl_socket_bind");
30  exit(EXIT_FAILURE);
31  }
32  portid = mnl_socket_get_portid(nl);
33 
34  nlh = mnl_nlmsg_put_header(buf);
35  nlh->nlmsg_type = (NFNL_SUBSYS_CTNETLINK << 8) | IPCTNL_MSG_CT_DELETE;
36  nlh->nlmsg_flags = NLM_F_REQUEST|NLM_F_ACK;
37  nlh->nlmsg_seq = seq = time(NULL);
38 
39  nfh = mnl_nlmsg_put_extra_header(nlh, sizeof(struct nfgenmsg));
40  nfh->nfgen_family = AF_INET;
41  nfh->version = NFNETLINK_V0;
42  nfh->res_id = 0;
43 
44  ct = nfct_new();
45  if (ct == NULL) {
46  perror("nfct_new");
47  return 0;
48  }
49 
50  nfct_set_attr_u8(ct, ATTR_L3PROTO, AF_INET);
51  nfct_set_attr_u32(ct, ATTR_IPV4_SRC, inet_addr("1.1.1.1"));
52  nfct_set_attr_u32(ct, ATTR_IPV4_DST, inet_addr("2.2.2.2"));
53 
54  nfct_set_attr_u8(ct, ATTR_L4PROTO, IPPROTO_TCP);
55  nfct_set_attr_u16(ct, ATTR_PORT_SRC, htons(20));
56  nfct_set_attr_u16(ct, ATTR_PORT_DST, htons(10));
57 
58  nfct_nlmsg_build(nlh, ct);
59 
60  ret = mnl_socket_sendto(nl, nlh, nlh->nlmsg_len);
61  if (ret == -1) {
62  perror("mnl_socket_recvfrom");
63  exit(EXIT_FAILURE);
64  }
65 
66  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
67  while (ret > 0) {
68  ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
69  if (ret <= MNL_CB_STOP)
70  break;
71  ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
72  }
73  if (ret == -1) {
74  perror("mnl_socket_recvfrom");
75  exit(EXIT_FAILURE);
76  }
77 
78  mnl_socket_close(nl);
79 
80  return 0;
81 }
void nfct_set_attr_u32(struct nf_conntrack *ct, const enum nf_conntrack_attr type, uint32_t value)
void nfct_set_attr_u16(struct nf_conntrack *ct, const enum nf_conntrack_attr type, uint16_t value)
struct nf_conntrack * nfct_new(void)
Definition: conntrack/api.c:75
void nfct_set_attr_u8(struct nf_conntrack *ct, const enum nf_conntrack_attr type, uint8_t value)