Skip to content

Instantly share code, notes, and snippets.

@dinhoabreu
Last active October 31, 2015 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinhoabreu/dfe4baab068e9c3f732a to your computer and use it in GitHub Desktop.
Save dinhoabreu/dfe4baab068e9c3f732a to your computer and use it in GitHub Desktop.
Whois formatter
#!/usr/bin/env php
<?php
function get(&$map, $pkeys, $default = '') {
$keys = explode('|', $pkeys);
foreach ($keys as $key) {
if (isset($map[$key])) {
return $map[$key];
}
}
return $default;
}
function whois($ip) {
exec("whois $ip | iconv -f latin1", $lines);
$var_lines = array_filter($lines, function ($line) {
return !!preg_match('/^[^%][^:]+:/', $line);
});
$vars = array('ip' => $ip);
foreach ($var_lines as $line) {
preg_match('/(^[^:]+):\s*(.*)\s*$/', $line, $matches);
$key = strtolower($matches[1]);
$value = $matches[2];
$vars[$key] = $value;
}
return $vars;
}
function whois_format($vars, $format) {
$pattern = '/{([^}]+)}/';
$replace = function ($matches) use ($vars) {
return get($vars, $matches[1]);
};
return preg_replace_callback($pattern, $replace, $format);
}
function whois_reader($fd, $format) {
while (($line = fgets($fd)) != false) {
$ip = trim($line);
if (!empty($ip)) {
$vars = whois($ip);
echo whois_format($vars, $format) . PHP_EOL;
}
}
}
function main() {
$argv = $_SERVER['argv'];
$format_default = '{ip} ({inetnum|cidr}, {owner|orgname}, {ownerid|orgid}, {responsible|city}, {country})';
$format = get($argv, 1, $format_default);
whois_reader(STDIN, $format);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment