Search code examples
phptraceroute

Get list of traceroute hops with php


shell_exec("traceroute IPaddress) returns traceroute to IPaddress (IPaddress), 30 hops max, 40 byte packets

How do I retrieve the actual list of hops so I can tell where a problem occurs?


Solution

  • Those messages are supposed to be written to stderr instead of the regular stdout, so I'm not too sure why you're seeing them appear in the output.

    Instead of shell_exec() I would recommend using exec() because it captures both the output AND the return code of the process:

    exec('traceroute example.com 2>&1', $out, $code);
    if ($code) {
        die("An error occurred while trying to traceroute: " . join("\n", $out);
    }
    print_r($out);
    

    To speed up the command a little you could use the -n option when you run traceroute to avoid having to do DNS lookups for the intermediate hops.

    Note that running traceroute can take a while; if you run it on the command line you can sometimes see lines with * * * in them, which can take ages!