How to store and search for IPv4 IP addresses in C more efficiently
I have the requirement that an efficient C data structure should take the IPv4 address as input and store it, searching through that stored data structure as needed.
Can we convert ipaddress to a string and store it in a data structure and check if it exists? If so, how can we achieve this!
Can you give me your valuable advice to continue?
Thanks in advance.
Instead of converting it to a string, store it as a 32-bit integer. Insert a new one into the right place in a linked list or array or other data structure, and you’re good to go. If the list is sorted, finding items is very easy because you can use binary search to locate items (or locate insertion points).
Personally, I would use arrays in many cases. This means that inserts are more complex (because you need to copy the member above the insertion point up 1, but it’s relatively fast (until you start talking about thousands of entries).
If you really need to be able to handle thousands of addresses, then a map structure might be better for you.