Skip to content

Instantly share code, notes, and snippets.

@kidGodzilla
Created February 22, 2022 20:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kidGodzilla/4b5db669c3bb67491b815a79337b9380 to your computer and use it in GitHub Desktop.
Save kidGodzilla/4b5db669c3bb67491b815a79337b9380 to your computer and use it in GitHub Desktop.
Geo IP node / express
const requestIp = require('request-ip');
function getIp (req) {
let ip = null;
try {
//ip = (req.headers['x-forwarded-for'] || '').split(',').pop() ||
// req.connection.remoteAddress ||
// req.socket.remoteAddress ||
// req.connection.socket.remoteAddress;
ip = requestIp.getClientIp(req);
} catch(e) {}
try {
if (req.headers['cf-connecting-ip']) ip = req.headers['cf-connecting-ip'];
} catch(e){}
return ip;
}
app.get('/location', (req, res) => {
let { ip } = req.query;
if (!ip) ip = getIp(req);
if (!ip || ip == '::1') return res.status(400).send('cannot request location from invalid IP or localhost');
var geo = geoip.lookup(ip);
if (!geo) return res.status(404).send('not found');
if (geo.city && geo.region && geo.country)
geo.location = `${ geo.city }, ${ geo.region }, ${ geo.country }`;
if (geo.ll) { geo.lat = geo.ll[0]; geo.long = geo.ll[1]; }
geo.ip = ip;
res.json(geo);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment