Skip to content

Instantly share code, notes, and snippets.

@jpdenford
Last active June 18, 2021 04:05
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 jpdenford/9678cc0745cec66b238557c056b3e30e to your computer and use it in GitHub Desktop.
Save jpdenford/9678cc0745cec66b238557c056b3e30e to your computer and use it in GitHub Desktop.
NodeJS script to check if a machine & port is reachable (e.g. telnet debugging replacement on minimal alpine image)
// USAGE
// node port-reachable.js google.com 80
// NOTE: if you want to get the file onto a machine without a text editor then try
// `echo "<copy & paste code here>" > port-reachable.js`
const dns = require('dns')
const net = require('net')
/**
* Find IP for dns
* e.g. dnsLookup('www.google.com', console.log)
*/
const dnsLookup = (domain, cb) => {
dns.lookup(domain, (err, ip, _) => {
if (err) throw err
cb(ip)
})
}
/**
* Establish connection to port
* e.g. connect(8080)('192.168.1.1')
*/
const connect = (port) => (ip) => {
const client = new net.Socket();
console.log('TRYING TO CONNECT TO: ' + ip + ':' + port)
client.connect(port, ip, () => {
console.log('CONNECTED!')
client.destroy()
})
client.on('error', console.error)
}
// e.g. connDomain('www.google.com', 443)
const connDomain = (domain, port) => dnsLookup(domain, connect(port))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment