Skip to content

Instantly share code, notes, and snippets.

@donavanm
Created February 5, 2011 21:01
Show Gist options
  • Save donavanm/812782 to your computer and use it in GitHub Desktop.
Save donavanm/812782 to your computer and use it in GitHub Desktop.
A simple IP address reflector.
<?php
// Think something like http://whatismyipaddress.com, but machine parsable,
// small, and fast(ish). Returns a json encoded hash.
// Will accept a port & optional timeout parameter. Attempts to make a TCP
// connection back to the host on specified port. Useful to see if you're
// externally reachable.
// I'm surprised noone else got here first. - donavanm
// Really PHP? What year is this again?
function get_host($ip){
$ptr= implode(".",array_reverse(explode(".",$ip))).".in-addr.arpa";
$host = dns_get_record($ptr,DNS_PTR);
if ($host == null) return $ip;
else return $host[0]['target'];
}
function test_port($host, $port, $timeout) {
$fp = @fsockopen($host, $port, $errno, $errstr, $timeout);
if (!$fp) {
return false;
} else {
fclose($fp);
return true;
}
}
// Get the client info
$host['ipaddress'] = $_SERVER["REMOTE_ADDR"];
if ($_SERVER['REMOTE_HOST']) {
$host['fqdn'] = $_SERVER['REMOTE_HOST'];
} else {
$host['fqdn'] = get_host($host['ipaddress']);
}
// Check for port parameter & test connection
if(!empty($_GET["port"])) {
if(!empty($_GET["timeout"]) && $_GET["timeout"] <= 3 ) { $timeout = $_GET["timeout"]; }
else { $timeout = 0.5; }
$port = $_GET["port"];
$host['port'][$port] = test_port($host['ipaddress'], $port, $timeout);
}
// setup some headers
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header("Content-type: application/json");
// Send body
echo json_encode($host);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment