Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you compare IP address?

Tags:

ip-address

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?

like image 874
MrValdez Avatar asked Oct 02 '08 03:10

MrValdez


People also ask

What is the difference in IP addresses?

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.

What are the 4 types of 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.

What are the two types of IP addresses how do they differ?

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.


2 Answers

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;
}
like image 188
gsaandy Avatar answered Sep 25 '22 05:09

gsaandy


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.

like image 44
sk. Avatar answered Sep 22 '22 05:09

sk.