程式語言 - Node.js - Ping Command



參考資訊:
https://blog.csdn.net/shunzi2016/article/details/117533724

main.js

var child = require('child_process');

async function start(client_ip) {
    var conn = false;

    await new Promise((resolve, reject) => {
        var ping = child.exec(`ping -c 30 ${client_ip}`);
        ping.stdout.on('data', function(data) {
            data = data.toString(data);
            
            if (data.indexOf('64 bytes from') > -1) {
                conn = true;
            }
        });

        ping.on('exit', function(code, signal) {
            resolve('ok');
        });
    });

    console.log('ping %s (result: %s)', client_ip, conn);
}

start('192.168.56.101');

執行

$ node main.js
    ping 192.168.56.101 (result: true)