patricia_node_t* ptree_add_rule(patricia_tree_t *ptree, char *line) { char *ip, *bits, *slash = NULL; struct in_addr addr4; struct in6_addr addr6; patricia_node_t *node = NULL; ip = line; bits = strchr(line, '/'); if(bits == NULL) bits = (char*)"/32"; else { slash = bits; slash[0] = '\0'; } /*bits存储掩码位数*/ bits++; ntop->getTrace()->traceEvent(TRACE_DEBUG, "Rule %s/%s", ip, bits); if(strchr(ip, ':') != NULL) { /* IPv6 */ if(inet_pton(AF_INET6, ip, &addr6) == 1) node = add_to_ptree(ptree, AF_INET6, &addr6, atoi(bits)); else ntop->getTrace()->traceEvent(TRACE_ERROR, "Error parsing IPv6 %s\n", ip); } else { /* IPv4 */ /*笔者注:个人认为也可以用inet_aton,在linux下测试感觉是一样的。*/ /* inet_aton(ip, &addr4) fails parsing subnets */ int num_octets; u_int ip4_0 = 0, ip4_1 = 0, ip4_2 = 0, ip4_3 = 0; u_char *ip4 = (u_char *) &addr4; if((num_octets = sscanf(ip, "%u.%u.%u.%u", &ip4_0, &ip4_1, &ip4_2, &ip4_3)) >= 1) { int num_bits = atoi(bits); ip4[0] = ip4_0, ip4[1] = ip4_1, ip4[2] = ip4_2, ip4[3] = ip4_3; if(num_bits > 32) num_bits = 32; if(num_octets * 8 < num_bits) ntop->getTrace()->traceEvent(TRACE_INFO, "Found IP smaller than netmask [%s]", line); //addr4.s_addr = ntohl(addr4.s_addr); node = add_to_ptree(ptree, AF_INET, &addr4, num_bits); } else { ntop->getTrace()->traceEvent(TRACE_ERROR, "Error parsing IPv4 %s\n", ip); } } if(slash) slash[0] = '/'; return(node); }
static void ptree_add_rule(patricia_tree_t *ptree, char *line) { char *ip, *bits; struct in_addr addr4; struct in6_addr addr6; ip = line; bits = strchr(line, '/'); if(bits == NULL) bits = (char*)"/32"; bits[0] = '\0'; bits++; ntop->getTrace()->traceEvent(TRACE_DEBUG, "Rule '%s'/'%s'\n", ip, bits); if(strchr(ip, ':') != NULL) { /* IPv6 */ if(inet_pton(AF_INET6, ip, &addr6) == 1) add_to_ptree(ptree, AF_INET6, &addr6, atoi(bits)); else ntop->getTrace()->traceEvent(TRACE_ERROR, "Error parsing IPv6 %s\n", ip); } else { /* IPv4 */ /* inet_aton(ip, &addr4) fails parsing subnets */ int num_octets, ip4_0 = 0, ip4_1 = 0, ip4_2 = 0, ip4_3 = 0; u_char *ip4 = (u_char *) &addr4; if((num_octets = sscanf(ip, "%u.%u.%u.%u", &ip4_0, &ip4_1, &ip4_2, &ip4_3)) >= 1) { ip4[0] = ip4_0, ip4[1] = ip4_1, ip4[2] = ip4_2, ip4[3] = ip4_3; if(num_octets * 8 < atoi(bits)) ntop->getTrace()->traceEvent(TRACE_WARNING, "Found ip smaller than netmask\n"); //addr4.s_addr = ntohl(addr4.s_addr); add_to_ptree(ptree, AF_INET, &addr4, atoi(bits)); } else { ntop->getTrace()->traceEvent(TRACE_ERROR, "Error parsing IPv4 %s\n", ip); } } }