Skip to content

Instantly share code, notes, and snippets.

@blha303
Created January 28, 2017 11:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blha303/09f38671839d60e49fd918f938fd3151 to your computer and use it in GitHub Desktop.
Save blha303/09f38671839d60e49fd918f938fd3151 to your computer and use it in GitHub Desktop.
A script to check if a given port is open on the connecting host. IP ranges included are for cloudflare, replace with an array containing your proxy server IP ranges
<?php
// A script to check if a given port is open on the connecting host.
// IP ranges included are for cloudflare, replace with an array containing your proxy server IP ranges
// https://b303.me/portopen.php?port=80
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
function cidr_match($ip, $ranges) {
$out = array();
foreach ($ranges as $range) {
list ($subnet, $bits) = explode('/', $range);
$ip = ip2long($ip);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $bits);
$subnet &= $mask; # nb: in case the supplied subnet wasn't correctly aligned
array_push($out, ($ip & $mask) == $subnet);
}
return $out;
}
function get_ip() {
$ranges = array("103.21.244.0/22","103.22.200.0/22","103.31.4.0/22",
"104.16.0.0/12","108.162.192.0/18","131.0.72.0/22",
"141.101.64.0/18","162.158.0.0/15","172.64.0.0/13",
"173.245.48.0/20","188.114.96.0/20","190.93.240.0/20",
"197.234.240.0/22","198.41.128.0/17","199.27.128.0/21",
"127.0.0.0/8");
if ( isset($_SERVER["HTTP_X_FORWARDED_FOR"]) && count(array_unique(cidr_match($_SERVER["HTTP_X_FORWARDED_FOR"], $ranges))) === 1 ) {
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
$ip = $_SERVER["REMOTE_ADDR"];
}
return $ip;
}
function check_port($ip, $port) {
$connection = @fsockopen($ip, $port, $errno, $errstr, 1);
if (is_resource($connection)) {
fclose($connection);
return true;
} else {
return false;
}
}
if (!isset($_GET["port"])) {
die(json_encode(array("error" => "Specify port parameter"), JSON_PRETTY_PRINT));
}
if (!is_numeric($_GET["port"])) {
die(json_encode(array("error" => "Numbers only please"), JSON_PRETTY_PRINT));
}
$ip = get_ip();
echo json_encode(
array(
"host" => $ip,
"port" => intval($_GET["port"]),
"open" => check_port(get_ip(), intval($_GET["port"]))
),
JSON_PRETTY_PRINT
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment