PHP Traceroute + Netstat Example

Below are some examples on how to do traceroute and netstat analysis in PHP on a Linux Server. This data could be incredibly useful if collected and analyzed or a script could be written to automatically analyze it with given configurable thresholds.

The example does a netstat and collects all the remote connections that are present. It then does some trace routes to find out more information. If you have access to an IP intelligence API, you could also find out more information about the remote connections being made to your Linux server.


//pass a destination ip address to any of these functions 

function getCarrier($dest) {
$out = '';
exec('traceroute '.$dest.' -w 0.5', $out, $code);
$i=-1;
foreach($out as $line) {
if(!preg_match("/\* \* \*/",$line)) {
$i++;
}
}
$hop_explode = explode(".",$out[$i]);
$carrier = $hop_explode[3];
return $carrier;
}

function getCarrierLoc($dest){
$out = '';
exec('traceroute '.$dest.' -w 0.5', $out, $code);
$i=-1;
foreach($out as $line) {
if(!preg_match("/\* \* \*/",$line)) {
$i++;
}
}
$hop_explode = explode(".",$out[$i]);
$carrier_loc = str_replace("1","",$hop_explode[2]);
return $carrier_loc;
}

function getHopCount($dest) {
$out = '';
exec('traceroute '.$dest.' -w 0.5', $out, $code);
$i=-1;
foreach($out as $line) {
if(!preg_match("/\* \* \*/",$line)) {
$i++;
}
}
return $i;
}

function netstat() {
$netstat = exec("netstat -tn | awk '{print $5}' | egrep -v '(localhost|\*\:\*|Address|and|servers|fff|127\.0\.0)' | sed 's/:[0-99999999].*//g'", $output);
foreach($output as $ip) {
sleep(1);
$hopCount = getHopCount($ip);
$carrierLoc = getCarrierLoc($ip);
$carrier = getCarrier($ip);

//now we could store this data, analyze this data, do trending and average calculations etc
//maybe do an ip lookup against whois or an ip intelligence API

}

}

//run our netstat
netstat();

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>