前两天其他项目组的同学说他们项目中的IP黑白名单要用到trie树,于是我好奇也自己实现了一个IP trie树接口.
在这里保存一下,方便备份以后使用,同时欢迎纠错和交流,希望有大神能指教更高效的算法.
1.头文件如下(iptrie.h)
1 #ifndef _IP_TRIE_H_ 2 #define _IP_TIRE_H_ 3 4 #define SPLIT_SIGN "." 5 #define IP_BINARY_LEN 32 6 7 typedef struct ip_trie_node 8 { 9 struct ip_trie_node *child[2]; //two child node 10 }ip_trie_node; 11 12 ip_trie_node *create_iptrie_node(); 13 14 void insert_iptrie_node(ip_trie_node *root,char ip[]); 15 16 int select_iptrie_node(ip_trie_node *root,char ip[]); 17 18 #endif
2.c文件如下(iptrie.c)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #include "iptrie.h" 6 7 /* 8 *name: itobinary 9 * 10 *param: 11 * num: orignal number; binary_str: dest string; index: the binary str copy index 12 * 13 *return: 14 * void 15 */ 16 void itobinary(int num,char binary_str[],int index) 17 { 18 if(binary_str == NULL) 19 { 20 return; 21 } 22 23 int i,bit = 0x01; 24 for(i = 0; i < 8; i++) 25 { //conver integer to 8 bit binary str 26 if((num & bit) != 0) 27 { //oprater & is lower than != 28 binary_str[index + 7 - i] = '1'; 29 } 30