My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Monday, June 08, 2015

ipcc, or better, how to retrieve a country via IP

In case you haven't read my previous post about The European's Cookie Law Absurdity, I suggest to understand what is this about and eventually go on.
The TL;DR version is that I've created, tested, and pushed to npm a very basic script that holds in memory a list of IPs, both version 4 and version 6, and returns a country code or a simple isEU(ip) boolean.

Why ipcc

Most databases are based on tokens and APIs. These are all wonderful, accurate, and fast, but for the EU Cookie's law absurdity all you might need is a boolean flag like "is this IP from EU or not?".
Well, now you can have such flag via node.js, assuming your server has a good amount of RAM and a decent CPU. It takes indeed a little more to bootstrap a website if ipcc is included, mostly due static Arrays holded directly on the file, Arrays that need to be parsed and hold on RAM.
// require it once
var ipcc = require('ipcc');

// for any request
function isRequestFromEU(request) {
  return ipcc.isEU(
    request.headers['x-forwarded-for'] ||
    request.connection.remoteAddress
  );
}

// in case you want to know the country
function whereIsRequestFrom(request) {
  return ipcc.resolve(
    request.headers['x-forwarded-for'] ||
    request.connection.remoteAddress
  );
}
Don't worry, if you ask multiple times different things using the same IP you will receive always the same previous answer stressing the CPU.
You can also read more on how it works on ipcc Github repository.

Special Thanks

Not to whoever wrote the EU law, but to db-ip.com, a wonderful updated service that provides a free, not so accurate, but extremely useful version of its countries database.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.