Skip to content

Instantly share code, notes, and snippets.

@alvises
Last active September 16, 2016 15:58
Show Gist options
  • Save alvises/d7525232410514b2da2e8834b71a96c1 to your computer and use it in GitHub Desktop.
Save alvises/d7525232410514b2da2e8834b71a96c1 to your computer and use it in GitHub Desktop.
app.get('/locate', function(req, res) {
//getting the ip of the client from the request headers or remoteAddress
var ip = req.param("ip");
ip = ip || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
var net = ip.split(".").slice(0,3).join(".")+".0"; //aaa.bbb.ccc.0
mongodb.connect("mongodb://127.0.0.1:27017/poetic_geoips",function(err,db){
if(err) throw err;
var ips = db.collection("ips");
ips.findOne({$or: [{ip: net}]},function(err,result){
if(err) throw err;
if(result) {
res.end(JSON.stringify({ip: ip,location: result.location}));
} else {
res.end(JSON.stringify({ip: ip}));
}
db.close();
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment