¿Cómo obtener el país de acuerdo con una determinada IP?


¿Alguien conoce una forma sencilla de recuperar el país de una dirección IP determinada? Preferiblemente en formato ISO_3166-1?

Author: Paul Ratazzi, 2008-08-04

14 answers

Mucha gente (incluida mi compañía) parece usar MaxMind GeoIP.

Tienen una versión gratuita GeoLite que no es tan precisa como la versión de pago, pero si usted está justo después de algo simple, puede ser lo suficientemente bueno.

 36
Author: Orion Edwards,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-08 00:17:40

Hay dos enfoques: usar un servicio de Internet y usar algún tipo de lista local (tal vez envuelta en una biblioteca). Lo que quieras dependerá de lo que estés construyendo.

Para servicios:

Para las listas:

 38
Author: Warren Blanchet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:00

Aquí hay un buen servicio gratuito con una API pública: http://www.hostip.info/use.html

 10
Author: Mark Harrison,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-04 05:21:59

Ipinfodb proporciona una base de datos y API gratuitas para IP a país y viceversa. Utilizan datos gratuitos de MaxMind. Los datos se actualizan cada mes, y es una gran alternativa gratuita con una precisión decente.

 8
Author: Donny Kurnia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-25 13:54:58

No se cuan preciso es hostip.info el sitio es. Acabo de visitar ese sitio, e informó que mi país es Canadá. Estoy en los EE.UU. y el ISP que mi oficina utiliza solo opera desde los EE.UU. Le permite corregir su conjetura, pero si está utilizando este servicio para rastrear a los visitantes del sitio web por país, no tendrá forma de saber si los datos son correctos. Por supuesto, sólo soy un punto de datos. He descargado la base de datos del país GeoLite, que es sólo una .archivo csv y mi dirección IP fue identificado correctamente como NOSOTROS.

Otro beneficio de la línea de productos MaxMind (de pago o gratis) es que tiene los datos, no incurre en el impacto de rendimiento de hacer una llamada de servicio web a otro sistema.

 5
Author: Chris Miller,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-08-04 14:02:14

El más preciso es Digital Elements NetAcuity...no es gratis, pero obtienes lo que pagas la mayor parte del tiempo.... Elemento digital

 2
Author: CSharpAtl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-27 03:04:41

Google clientlocation devuelve (mi ejemplo)

latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
location = "IP location: " + getFormattedLocation();
document.getElementById("location").innerHTML = location;
 2
Author: Niklas Rosencrantz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-13 13:25:21

Puede utilizar la solución proporcionada para esta pregunta.

Pero devuelve un código de país de 2 dígitos.

 2
Author: zak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:20

Pruebe este código php

  <?php  $ip = $_SERVER['REMOTE_ADDR'];
    $json = file_get_contents("http://api.easyjquery.com/ips/?ip=".$ip."&full=true");
    $json = json_decode($json,true);
    $timezone = $json[localTimeZone];?>
 2
Author: pckabeer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-30 08:07:35

Puedes usar mi servicio, http://ipinfo.io , para esto. La API devuelve un montón de detalles diferentes sobre una dirección IP:

$ curl ipinfo.io/8.8.8.8
{
  "ip": "8.8.8.8",
  "hostname": "google-public-dns-a.google.com",
  "loc": "37.385999999999996,-122.0838",
  "org": "AS15169 Google Inc.",
  "city": "Mountain View",
  "region": "CA",
  "country": "US",
  "phone": 650
}

Si solo buscas el código de país, solo necesitas agregar / country a la URL:

$ curl ipinfo.io/8.8.8.8/country
US

Aquí hay una función PHP genérica que podría usar:

function ip_details($ip) {
    $json = file_get_contents("http://ipinfo.io/{$ip}");
    $details = json_decode($json);
    return $details;
}

$details = ip_details("8.8.8.8");

echo $details->city;     // => Mountain View
echo $details->country;  // => US
echo $details->org;      // => AS15169 Google Inc.
echo $details->hostname; // => google-public-dns-a.google.com

He utilizado la IP 8.8.8.8 en estos ejemplos, pero si desea detalles para la IP del usuario simplemente pase $_SERVER['REMOTE_ADDR'] en su lugar. Más detalles están disponibles en http://ipinfo.io/developers

 2
Author: Ben Dowling,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-26 04:49:49

Utilice la función ipToCountry (ip ip) de http://www.mmtutorialvault.com/php-ip-to-country-function /

 1
Author: saifur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-27 17:54:01

Puede usar API de servicio web que hacen este trabajo como:

see example of service: http://ip-api.com and usage: http://whatmyip.info
 1
Author: user3463375,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-28 12:57:32

Véase ipdata.co que le da varios puntos de datos de una dirección ip.

La API es bastante rápida, con 10 endpoints globales cada uno capaz de manejar >800M llamadas diarias.

Aquí hay un ejemplo de rizo;

curl https://api.ipdata.co/78.8.53.5
{
    "ip": "78.8.53.5",
    "city": "G\u0142og\u00f3w",
    "region": "Lower Silesia",
    "region_code": "DS",
    "country_name": "Poland",
    "country_code": "PL",
    "continent_name": "Europe",
    "continent_code": "EU",
    "latitude": 51.6461,
    "longitude": 16.1678,
    "asn": "AS12741",
    "organisation": "Netia SA",
    "postal": "67-200",
    "currency": "PLN",
    "currency_symbol": "z\u0142",
    "calling_code": "48",
    "flag": "https://ipdata.co/flags/pl.png",
    "emoji_flag": "\ud83c\uddf5\ud83c\uddf1",
    "time_zone": "Europe/Warsaw",
    "is_eu": true,
    "suspicious_factors": {
        "is_tor": false
    }
}⏎  
 0
Author: Jonathan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-18 19:05:11

Puede probar la base de datos gratuita IP2Location LITE

Para crear la tabla en MySQL

CREATE DATABASE ip2location;
USE ip2location;
CREATE TABLE `ip2location_db1`(
    `ip_from` INT(10) UNSIGNED,
    `ip_to` INT(10) UNSIGNED,
    `country_code` CHAR(2),
    `country_name` VARCHAR(64),
    INDEX `idx_ip_to` (`ip_to`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

Para importar los datos

LOAD DATA LOCAL
    INFILE 'IP2LOCATION-LITE-DB1.CSV'
INTO TABLE
    `ip2location_db1`
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 0 LINES;

Código PHP para consultar el MySQL

<?php
// Replace this MYSQL server variables with actual configuration
$mysql_server = "mysql_server.com";
$mysql_user_name = "UserName";
$mysql_user_pass = "Password";

// Retrieve visitor IP address from server variable REMOTE_ADDR
$ipaddress = $_SERVER["REMOTE_ADDR"];

// Convert IP address to IP number for querying database
$ipno = Dot2LongIP($ipaddress);

// Connect to the database server
$link = mysql_connect($mysql_server, $mysql_user_name, $mysql_user_pass) or die("Could not connect to MySQL database");

// Connect to the IP2Location database
mysql_select_db("ip2location") or die("Could not select database");

// SQL query string to match the recordset that the IP number fall between the valid range
$query = "SELECT * FROM ip2location_db1 WHERE $ipno <= ip_to LIMIT 1";

// Execute SQL query
$result = mysql_query($query) or die("IP2Location Query Failed");

// Retrieve the recordset (only one)
$row = mysql_fetch_object($result);

// Keep the country information into two different variables
$country_code = $row->country_code;
$country_name = $row->country_name;

echo "Country_code: " . $country_code . "<br/>";
echo "Country_name: " . $country_name . "<br />";

// Free recordset and close database connection
mysql_free_result($result);
mysql_close($link);

// Function to convert IP address (xxx.xxx.xxx.xxx) to IP number (0 to 256^4-1)
function Dot2LongIP ($IPaddr) {
 if ($IPaddr == "")
 {
   return 0;
 } else {
   $ips = explode(".", $IPaddr);
   return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
 }
}
?>
 0
Author: Vlam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-27 05:32:26