Skip to content

Instantly share code, notes, and snippets.

@cjwfuller
Last active May 17, 2016 16:44
Show Gist options
  • Save cjwfuller/5524942 to your computer and use it in GitHub Desktop.
Save cjwfuller/5524942 to your computer and use it in GitHub Desktop.
Get external IP address in Node.js
var ipModule = (function() {
// Private stuff
var my = {};
var options = {
hostname: 'jsonip.com'
};
// Get the external IP address of this server using the JSON IP server
my.getIP = function(cb) {
var ipAddr = '';
// Make the web request
var req = http.request(options, function(res) {
res.setEncoding('utf8');
// Make sure we get all the data from the response
res.on('data', function (chunk) {
ipAddr += chunk;
});
// Response has finished so callback, null is because we should
// indicate there was no error
res.on('end', function() {
cb(null, JSON.parse(ipAddr).ip);
});
});
// We must say we have finished the request
req.end();
}
return my;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment