12 typedef struct _ipslot {
29 static int readline(int fd,char **outp) {
31 char *curp = stream.data + stream.cur;
32 char *endp = stream.data + stream.end;
34 while ( curp < endp ) {
35 if ( *(curp++) == '\n' ) {
36 stream.cur = curp - stream.data;
41 if ( top != stream.data ) {
43 while ( top < endp ) {
47 stream.end = endp - stream.data;
50 ssize_t n = read( fd, endp, BUFSZ - stream.end );
52 if ( stream.end == 0 ) {
53 return -1; // No more data
55 (*outp) = stream.data;
63 // Scan to NUL, CR or c. Return pointer not including character.
64 static char *scanto(char *p, char c) {
65 while ( *p && *p != '\n' && *p != c ) {
71 static int parse_addr(char *line,ipslot *addr) {
72 char *end = scanto( line, '\n' );
73 char *slash = scanto( line, '/' );
75 if ( inet_pton( AF_INET, line, addr->data ) == 0 ) {
77 } if ( inet_pton( AF_INET6, line, addr->data ) == 0 ) {
82 if ( slash != end && sscanf( slash+1, "%u", &addr->bits ) != 1 ) {
88 static void add_entry(ipslot *tmp) {
89 ipslot *p = (ipslot *) malloc( sizeof( ipslot ) );
90 memmove( p, tmp, sizeof( ipslot ) );
91 if ( table.data.size == table.fill ) {
92 (void) pvector_resize( &table.data, table.fill + 256, 0, 0 );
94 pvector_set( &table.data, table.fill++, p );
97 static void load_file(const char *filename) {
98 int fd = open( filename, O_RDONLY );
105 while ( ( n = readline( fd, &line ) ) >= 0 ) {
107 if ( parse_addr( line, &addr ) ) {
108 fprintf( stderr, "Bad address: %s\n", line );
115 static int int_reclaim(pvector *pv,unsigned long index,void *item,void *data) {
119 static int dumpitem(const unsigned long index,const void *item) {
120 fprintf( stdout, "[%ld] %p\n", index, item );
124 static int dump_ipslot(const unsigned long index,const void *item) {
125 static char buffer[100];
126 ipslot *ip = (ipslot*) item;
127 const char *p = inet_ntop( (ip->bits <= 32)? AF_INET : AF_INET6,
128 ip->data, buffer, 100 );
130 fprintf( stdout, "[%ld] %s/%d\n", index, p, ip->bits );
134 int main(int argc,char **argv) {
135 pvector test = { 0 };
136 pvector_resize( &test, 100, 0, 0 );
137 pvector_set( &test, 5, (void*) 500 );
138 pvector_set( &test, 55, (void*) 600 );
139 //pvector_set( &test, 550, (void*) 800 );
140 pvector_resize( &test, 300, 0, 0 );
141 pvector_set( &test, 55, (void*) 650 );
142 pvector_resize( &test, 30000, 0, 0 );
143 pvector_set( &test, 22255, (void*) 26 );
144 pvector_dump( &test, dumpitem );
145 pvector_resize( &test, 100, int_reclaim, 0 );
146 pvector_set( &test, 5, (void*) 2 );
147 pvector_dump( &test, dumpitem );
150 for ( i = 1; i < argc; i++ ) {
151 load_file( argv[ i ] );
153 pvector_dump( &table.data, dump_ipslot );