Node, Chicken my IP!
ip man!
Every-now-and-then you have a need to retrieve your IP. Yeah, we all know you can go to IPChicken etc...and get it from there. I mean that is if you are a human and not a robot, right?
What if your app in a cloud has a need to retrieve user's IP? In my case, a Node Express app! Just like everyone I am flying in Amazon Cloud and so I stumbled upon Amazon's check-ip service. Simply clicking on http://checkip.amazonaws.com will return your IP address. All cool, but how exactly do you retrieve it through your app? Easy peasy!
I am using Node Js with Express.
First, I will create a simple route definition. Which will allow me to make a rest call like,
http://localhost:3000/cloud/ip
Here is my route definition.
router.get('/ip', cloud.getIp); // retrieve user ip address through amazon service
and here is my callback. Upon calling cloud.getIp
my route will call this function.
const http = require('http');
const getIp = (req, res) => {
let options = {
host : 'checkip.amazonaws.com'
};
http.get (options, (ipdata) => {
ipdata.on ('data', (ip) => {
res.send ({ status : 'success', data : ip.toString().trim() });
});
}).on ('error', (e) => {
res.send ({ status : 'failure', data : e });
});
});
Now, curl the route or open up a REST client to retrieve the IP. Voila! Do you see your IP? Short and sweet, right?
Whoa! Node just chickened my IP!
Cheers!
Hi, I am Ritesh Patel. I live in a beautiful town surrounded by the mountains. C&O Canal is few miles away. State parks are only a distance away & bike trails galore. It is home sweet home Frederick, MD. A passionate developer. Love to cook. Enjoy playing "Bollywood Tunes" on my harmonica. Apart from that just a normal guy.