Created
February 22, 2022 20:08
-
-
Save kidGodzilla/4b5db669c3bb67491b815a79337b9380 to your computer and use it in GitHub Desktop.
Geo IP node / express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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