I'm playing around with some code for no particular reason. Given an IP address (IP4 or IP6), it is mostly successful at determining the country. It's not super fast like using IP2Country, but it's not terribly slow. I'm wondering if any of you have experience with this, and if it's generally regarded as unreliable, or any other negative consequences. Check it out:
PHP Code:
<?php
function _request( $ip, $type, $server )
{
$search = $type == 'registry'
? 'whois:'
: 'country:';
$f = fsockopen( $server, 43, $errno, $errstr, 5 );
if( ! $f )
{
fclose($f);
return FALSE;
}
/*$ip = $type == 'country'
? 'n ' . $ip
: $ip;*/
fwrite( $f, $ip . "\r\n" );
$found = FALSE;
do{
$line = fgets($f, 1024);
//echo $line . '<br />';
if( stripos( $line, $search ) !== FALSE )
{
$parts = explode( ':', $line );
$value = trim( $parts[1] );
$found = TRUE;
}
}
while( ! feof($f) && $found === FALSE );
fclose($f);
return isset( $value )
? $value
: FALSE;
}
function determine_regional_registry( $ip )
{
return _request( $ip, 'registry', 'whois.iana.org' );
}
function determine_country( $ip, $server )
{
return _request( $ip, 'country', $server );
}
$ip = '204.86.16.251'; // US
$ip = '209.105.243.106'; // US
$ip = '123.77.194.109'; // CN
$ip = '188.143.234.155'; // RU
$ip = '61.131.86.89'; // CN
$ip = '27.151.61.241'; // CN
$ip = '195.154.204.88'; // FR
$ip = '188.123.126.139'; // GR
$ip = '110.232.248.115'; // IN
$ip = '45.72.0.253'; // Blank ???
$ip = "103.254.205.75"; // IN
if( $server = determine_regional_registry( $ip ) )
{
echo $server . ' says IP address ' . $ip . ' is in: ';
echo determine_country( $ip, $server );
}