Last active
May 17, 2016 16:44
-
-
Save cjwfuller/5524942 to your computer and use it in GitHub Desktop.
Get external IP address in Node.js
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
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