Skip to content

Instantly share code, notes, and snippets.

@versionsix
Forked from aaronhurt/cymru-lookup.php
Created April 22, 2017 21:50
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 versionsix/6337a935451b5389f6a7ea21e424952b to your computer and use it in GitHub Desktop.
Save versionsix/6337a935451b5389f6a7ea21e424952b to your computer and use it in GitHub Desktop.
testing the cymru netcat access
<?php
/* test host list */
$hostlist = array(
'96.4.1.22',
'207.191.191.90',
'8.8.8.8'
);
/* do the lookup */
function lookup(array $hosts = array()) {
/* open the socket */
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
or die("Unable to create socket\n");
/* connect to cymru */
socket_connect($sock, 'whois.cymru.com', 43)
or die("Unable to connect to whois.cymru.com\n");
/* generate request */
$request = sprintf("begin\nverbose\n%s\nend\n", join("\n", $hosts));
/* write the request */
socket_write($sock, $request, strlen($request))
or die("Unable to write request to socket\n");
/* array of labels */
$labels = array(
0 => 'as',
1 => 'ip',
2 => 'prefix',
3 => 'cc',
4 => 'registry',
5 => 'allocated',
6 => 'name'
);
/* init output */
$output = array();
/* loop through the results */
while (true) {
/* read line from socket */
$line = @socket_read($sock, 2048, PHP_NORMAL_READ);
/* nothing left to read */
if (!strlen($line)) break;
/* break line on pipes */
$parts = explode('|', $line, 7);
/* skip lines that don't contain all the fields */
if (count($parts) !== 7) continue;
/* temp array */
$temps = array();
/* parse the line and assign labels */
foreach ($labels as $idx => $name) {
/* build array */
$temps[$name] = trim($parts[$idx]);
}
/* append to output */
$output[$temps['prefix']] = $temps;
}
/* close socket */
socket_close($sock);
/* return json */
return json_encode($output, JSON_PRETTY_PRINT);
}
/* call lookup and print results */
printf("%s\n", lookup($hostlist));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment