April 17th, 2006

Perform a Trace Route (tracert) with PHP

This is a handy little code snippet to trace a packet's route from the web server to a remote host. The code uses regualr expressions to validate the IP address of the remote host, and the code also protects against form submission spoofing.


<?php
ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);

// Obtain POST data.
$trace_ip_addr = $_POST['trace_ip_addr']; // input

// Remove any slashes if Magic Quotes GPC is enabled.
if (get_magic_quotes_gpc())
{
    $trace_ip_addr = stripslashes($trace_ip_addr);
}

if ($_POST['submit'] == 'Trace') // Form has been submitted.
{
    echo '<div class="output">' . "\n";
    if (strlen($trace_ip_addr) <= 15)
    {
	// use regular expression to check for valid IP adress
        if (ereg('^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$', $trace_ip_addr))
        {
            // Display result.

            echo '<pre>' . "\n" .
                 'traceroute ' . $trace_ip_addr . "\n\n";

            system('traceroute ' . $trace_ip_addr); // Trace IP address.

            echo '</pre>' . "\n" .
                 '<p>Trace complete.</p>' . "\n";
        }
        else
        {
	   // regular expression determined invalid IP adress
            echo '<p>Please enter a valid IP address.</p>' . "\n";
        }
    }
    else
    {
        echo '<p>An illegal operation was encountered.</p>' . "\n";
    }
    echo '</div>' . "\n";
}
?>
<html>
<head>
<title>Trace</title>
</head>
<body>
<h1>Trace</h1>
<form method="post">
<p><label for="trace_ip_addr">IP address:</label><br />
<input name="trace_ip_addr" id="trace_ip_addr" type="text" value="<?php echo $_POST['submit'] == 'Trace' ? htmlentities($trace_ip_addr, ENT_QUOTES) : '127.0.0.1'; ?>" size="40" maxlength="15" /></p>
<p><input type="submit" name="submit" value="Trace" /></p>
</form>
<p>Trace may take a while, please be patient.</p>
</body>
</html>

This code is adapted from a snippet I found on DaniWeb

  • Share/Bookmark

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word