PHP Code

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.

ini_set('display_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
// Obtain POST data.
$trace_ip_addr = $_POST&#91;'trace_ip_addr'&#93;; // input
// Remove any slashes if Magic Quotes GPC is enabled.
if (get_magic_quotes_gpc())
    $trace_ip_addr = stripslashes($trace_ip_addr);
if ($_POST&#91;'submit'&#93; == '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('^&#91;0-9&#93;{1,3}\.&#91;0-9&#93;{1,3}\.&#91;0-9&#93;{1,3}\.&#91;0-9&#93;{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";
	   // regular expression determined invalid IP adress
            echo '<p>Please enter a valid IP address.</p>' . "\n";
        echo '<p>An illegal operation was encountered.</p>' . "\n";
    echo '</div>' . "\n";
<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&#91;'submit'&#93; == 'Trace' ? htmlentities($trace_ip_addr, ENT_QUOTES) : ''; ?>" size="40" maxlength="15" /></p>
<p><input type="submit" name="submit" value="Trace" /></p>
<p>Trace may take a while, please be patient.</p>

This code is adapted from a snippet I found on DaniWeb


Leave a Reply

Your email address will not be published. Required fields are marked *

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.
Anti-spam image