For my server app, I need to check if an ip address is in our blacklist.
What is the most efficient way of comparing ip addresses? Would converting the IP address to integer and comparing them efficient?
A public IP address identifies you to the wider internet so that all the information you're searching for can find you. A private IP address is used within a private network to connect securely to other devices within that same network. Each device within the same network has a unique private IP address.
An internet protocol (IP) address allows computers to send and receive information. There are four types of IP addresses: public, private, static, and dynamic.
Every individual or business with an internet service plan will have two types of IP addresses: their private IP addresses and their public IP address. The terms public and private relate to the network location — that is, a private IP address is used inside a network, while a public one is used outside a network.
The following one is I've used in JavaScript
function isValidIPv4Range(iPv4Range = '') {
if (IP_V4_RANGE_REGEX.test(iPv4Range)) {
const [fromIp, toIp] = iPv4Range.split('-');
if (!isValidOctets(fromIp) || !isValidOctets(toIp)) {
return false;
}
const convertToNumericWeight = ip => {
const [octet1, octet2, octet3, octet4] = ip.split('.').map(parseInt);
return octet4 + (octet3 * 256) + (octet2 * 256 * 256) + (octet1 * 256 * 256 * 256);
};
return convertToNumericWeight(fromIp) < convertToNumericWeight(toIp);
}
return false;
}
Depends what language you're using, but an IP address is usually stored as a 32-bit unsigned integer, at least at the network layer, making comparisons quite fast. Even if it's not, unless you're designing a high performance packet switching application it's not likely to be a performance bottleneck. Avoid premature optimization - design your program for testability and scalability and if you have performance problems then you can use a profiler to see where the bottlenecks are.
Edit: to clarify, IPv4 addresses are stored as 32-bit integers, plus a netmask (which is not necessary for IP address comparisons). If you're using the newer and currently more rare IPv6, then the addresses will be 128 bits long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With