基础用法
系统配置
### 开启流数据包统计(packets和bytes)
# echo "net.netfilter.nf_conntrack_acct=1" >> /etc/sysctl.conf
### 开启流持续时间统计(delta-time)
# echo "net.netfilter.nf_conntrack_timestamp=1" >> /etc/sysctl.conf
# sysctl -p /etc/sysctl.conf
命令使用
- 显示当前正在被追踪的流
# conntrack -L -o ktimestamp
tcp 6 431666 ESTABLISHED src=10.0.0.2 dst=20.0.0.6 sport=33715 dport=22 packets=17 bytes=2094 src=20.0.0.6 dst=10.0.0.2 sport=22 dport=33715 packets=14 bytes=1870 [ASSURED] mark=0 zone=1 delta-time=336 [start=Wed Sep 13 15:48:40 2017] use=1
icmp 1 29 src=20.0.0.11 dst=20.0.0.6 type=8 code=0 id=40449 packets=5 bytes=420 src=20.0.0.6 dst=20.0.0.11 type=0 code=0 id=40449 packets=5 bytes=420 mark=0 zone=9 delta-time=4 [start=Wed Sep 13 15:55:46 2017] use=1
- 监控流事件
# conntrack -E -o ktimestamp
[NEW] tcp 6 120 SYN_SENT src=10.0.0.2 dst=20.0.0.6 sport=33717 dport=22 [UNREPLIED] src=20.0.0.6 dst=10.0.0.2 sport=22 dport=33717 zone=1
[DESTROY] tcp 6 src=10.0.0.2 dst=20.0.0.6 sport=33717 dport=22 packets=31 bytes=3042 src=20.0.0.6 dst=10.0.0.2 sport=22 dport=33717 packets=23 bytes=2666 [ASSURED] zone=1 delta-time=142 [start=Wed Sep 13 16:07:06 2017] [stop=Wed Sep 13 16:09:28 2017]
高级用法
-L命令实现
# vim main.c
#include <stdio.h>
#include <assert.h>
#include <libmnl/libmnl.h>
#include <libnetfilter_conntrack/libnetfilter_conntrack.h>
static int dump_cb(enum nf_conntrack_msg_type type, struct nf_conntrack *ct, void *data)
{
char buf[1024];
unsigned int op_type = NFCT_O_DEFAULT;
unsigned int op_flags = 0;
nfct_snprintf(buf, sizeof(buf), ct, NFCT_T_UNKNOWN, op_type, op_flags);
printf("%s
", buf);
return NFCT_CB_CONTINUE;
}
int main()
{
struct nfct_handle *cth = nfct_open(CONNTRACK, 0);
assert(cth != NULL);
nfct_callback_register(cth, NFCT_T_ALL, dump_cb, NULL);
struct nfct_filter_dump *filter_dump = nfct_filter_dump_create();
assert(filter_dump != NULL);
nfct_filter_dump_set_attr_u8(filter_dump, NFCT_FILTER_DUMP_L3NUM, AF_INET);
nfct_query(cth, NFCT_Q_DUMP_FILTER, filter_dump);
printf("============测试一下=================
");
nfct_query(cth, NFCT_Q_DUMP_FILTER, filter_dump);
nfct_filter_dump_destroy(filter_dump);
nfct_close(cth);
}
# yum install -y libnetfilter_conntrack-devel libmnl-devel
# gcc main.c -lnetfilter_conntrack -lmnl -o ct
问题处理
在容器中运行conntrack命令报错
conntrack v1.4.4 (conntrack-tools): Operation failed: sorry, you must be root or get CAP_NET_ADMIN capability to do this
### 解决办法,容器运行需要添加如下参数
# docker run --privileged=true --net=host