因工做須要對Netflow v9協議進行了一些分析,其靈活的模板機制使人印象深入。本着無代碼無真相的原則,使用libpcap庫作了一個簡單的demo示例,其中對Netflow v9中須要獲取的信息作了以下定義: node
typedef struct _netflow_v9_record { u_int8_t ip_ver; union { u_int32_t v4_srcaddr; struct in6_addr v6_srcaddr; } srcaddr; union { u_int32_t v4_dstaddr; struct in6_addr v6_dstaddr; } dstaddr; union { u_int32_t v4_nexthop; struct in6_addr v6_nexthop; } nexthop; u_int32_t orig_pkts; u_int32_t orig_bytes; u_int32_t reply_pkts; u_int32_t reply_bytes; u_int32_t first; u_int32_t last; u_int16_t srcport; u_int16_t dstport; u_int16_t icmp_type; u_int16_t src_vlan; u_int16_t dst_vlan; u_int8_t src_mac[6]; u_int8_t dst_mac[6]; u_int8_t prot; u_int8_t tos; } __attribute__((__packed__)) netflow_v9_record;仿netfilter-conntrack中tuple機制,作連接管理結構以下(未單獨提取tuple):
struct link_info_t { struct hlist_node link; netflow_v9_record record; /* there will be something else */ }; static struct link_info_t tmp_link; static struct hlist_head link_table[TABLE_SIZE]; static inline uint16_t hash_ip_port(struct link_info_t link) { return ((link.record.dstaddr.v4_dstaddr ^ link.record.srcaddr.v4_srcaddr) ^ \ (link.record.dstport ^ link.record.srcport)) & 0x1ffff; }由於沒有單獨將tuple提取出來,且將ORIGINAL與REPLY作爲同一個tuple以標示同一條鏈接,因此對鏈接的判斷和統計繁瑣了一些:
hlist_for_each_entry(cur_link, pos, head, link) { if (cur_link->record.srcaddr.v4_srcaddr == tmp_link.record.srcaddr.v4_srcaddr && \ cur_link->record.dstaddr.v4_dstaddr == tmp_link.record.dstaddr.v4_dstaddr && \ cur_link->record.srcport == tmp_link.record.srcport && \ cur_link->record.dstport == tmp_link.record.dstport) { cur_link->record.orig_pkts++; cur_link->record.orig_bytes += len; flag = 1; break; } else if (cur_link->record.srcaddr.v4_srcaddr == tmp_link.record.dstaddr.v4_dstaddr && \ cur_link->record.dstaddr.v4_dstaddr == tmp_link.record.srcaddr.v4_srcaddr && \ cur_link->record.srcport == tmp_link.record.dstport && \ cur_link->record.dstport == tmp_link.record.srcport) { cur_link->record.reply_pkts++; cur_link->record.reply_bytes += len; flag = 1; break; } }gen_nfv9模塊負責構造、發送數據包,做爲示例,僅手工構造了包含兩個字段信息的template與數據信息,由lo:9999發送。
(不能添加附件??...:-(...) ui