Search code examples
cpacketlookup-tableslibpcap

IP Lookup Table in Memory C


I'm currently experimenting with libpcap and various C applications and trying to do accomplish the following. Upon program initialization, I'd like to load IPs from a file and store them in memory. When I receive some packet details for processing, I'd like to compare an IP with the set of IP's loaded into memory.

What's the best way/data struct to implement this in C? I need to accommodate a list growth and efficient matching, so I feel like a simple lookup array would be a wrong solution. Help?


Solution

  • The absolutely least amount of work, for really-decent performance, would probably be to just use an array of uint32_t.

    When loading your data, throw each IP into the array, using realloc() to grow it as necessary. Remember to use a sane growth pattern, doubling the allocated length each time it runs out is common and would probably work nicely.

    After load, sort the array using a simple http://linux.die.net/man/3/qsort call.

    Then you can search the array quickly using bsearch().

    Since this uses only standard functions, it will be very small code-wise, and thus easy to understand and quick to write. No dependencies, and no time spent either chasing down sane libraries, or writing your own higher-level data structures. But since it uses binary search, it will be pretty fast.