• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
data_cb(const struct nlmsghdr * nlh,void * data)12 static int data_cb(const struct nlmsghdr *nlh, void *data)
13 {
14 	struct nf_conntrack *ct;
15 	char buf[4096];
16 
17 	ct = nfct_new();
18 	if (ct == NULL)
19 		return MNL_CB_OK;
20 
21 	nfct_nlmsg_parse(nlh, ct);
22 
23 	nfct_snprintf(buf, sizeof(buf), ct, NFCT_T_UNKNOWN, NFCT_O_DEFAULT, 0);
24 	printf("%s\n", buf);
25 
26 	nfct_destroy(ct);
27 
28 	return MNL_CB_OK;
29 }
30 
main(void)31 int main(void)
32 {
33 	struct mnl_socket *nl;
34 	struct nlmsghdr *nlh;
35 	struct nfgenmsg *nfh;
36 	char buf[MNL_SOCKET_BUFFER_SIZE];
37 	unsigned int seq, portid;
38 	struct nf_conntrack *ct;
39 	int ret;
40 
41 	nl = mnl_socket_open(NETLINK_NETFILTER);
42 	if (nl == NULL) {
43 		perror("mnl_socket_open");
44 		exit(EXIT_FAILURE);
45 	}
46 
47 	if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
48 		perror("mnl_socket_bind");
49 		exit(EXIT_FAILURE);
50 	}
51 	portid = mnl_socket_get_portid(nl);
52 
53 	nlh = mnl_nlmsg_put_header(buf);
54 	nlh->nlmsg_type = (NFNL_SUBSYS_CTNETLINK << 8) | IPCTNL_MSG_CT_GET;
55 	nlh->nlmsg_flags = NLM_F_REQUEST|NLM_F_ACK;
56 	nlh->nlmsg_seq = seq = time(NULL);
57 
58 	nfh = mnl_nlmsg_put_extra_header(nlh, sizeof(struct nfgenmsg));
59 	nfh->nfgen_family = AF_INET;
60 	nfh->version = NFNETLINK_V0;
61 	nfh->res_id = 0;
62 
63 	ct = nfct_new();
64 	if (ct == NULL) {
65 		perror("nfct_new");
66 		return 0;
67 	}
68 
69 	nfct_set_attr_u8(ct, ATTR_L3PROTO, AF_INET);
70 	nfct_set_attr_u32(ct, ATTR_IPV4_SRC, inet_addr("1.1.1.1"));
71 	nfct_set_attr_u32(ct, ATTR_IPV4_DST, inet_addr("2.2.2.2"));
72 
73 	nfct_set_attr_u8(ct, ATTR_L4PROTO, IPPROTO_TCP);
74 	nfct_set_attr_u16(ct, ATTR_PORT_SRC, htons(20));
75 	nfct_set_attr_u16(ct, ATTR_PORT_DST, htons(10));
76 
77 	nfct_nlmsg_build(nlh, ct);
78 
79 	ret = mnl_socket_sendto(nl, nlh, nlh->nlmsg_len);
80 	if (ret == -1) {
81 		perror("mnl_socket_recvfrom");
82 		exit(EXIT_FAILURE);
83 	}
84 
85 	ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
86 	while (ret > 0) {
87 		ret = mnl_cb_run(buf, ret, seq, portid, data_cb, NULL);
88 		if (ret <= MNL_CB_STOP)
89 			break;
90 		ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
91 	}
92 	if (ret == -1) {
93 		perror("mnl_socket_recvfrom");
94 		exit(EXIT_FAILURE);
95 	}
96 
97 	mnl_socket_close(nl);
98 
99 	return 0;
100 }
101