Skip to content

Instantly share code, notes, and snippets.

@atmosx
Created March 22, 2022 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atmosx/9359726c9f6cc385d858d56e674cdb80 to your computer and use it in GitHub Desktop.
Save atmosx/9359726c9f6cc385d858d56e674cdb80 to your computer and use it in GitHub Desktop.
get external IP
var ip = require("ip");
var http = require('http');
var host = "ip-1-2-3-4.ec2.internal"
function getExternalIP(host) {
if (host.includes('ec2.internal')){
console.log("This is an EC2 instance. Fetching 'listenIp' via HTTP");
http.get({'host': 'checkip.amazonaws.com', 'port': 80, 'path': '/'}, function(resp) {
resp.on('data', function(ip) {
return ip;
});
});
} else {
return ip.address();
}
}
i = getExternalIP(host)
console.log("IP is " + i)
// $ node file.js
// This is an EC2 instance. Fetching 'listenIp' via HTTP
// IP is undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment