특정 IP에 따라 국가를 얻는 방법은 무엇입니까?
주어진 IP 주소로 국가를 검색하는 간단한 방법을 아는 사람이 있습니까? ISO_3166-1 형식이 바람직합니까?
많은 사람들 (저희 회사 포함)이 MaxMind GeoIP를 사용하는 것 같습니다.
그들은 유료 버전만큼 정확하지 않은 무료 버전 GeoLite 를 가지고 있지만 간단한 것을 추구한다면 충분할 수 있습니다.
두 가지 접근 방식이 있습니다. 인터넷 서비스 사용과 일종의 로컬 목록 사용 (아마도 라이브러리에 래핑되어 있음)입니다. 당신이 원하는 것은 당신이 무엇을 만들고 있는지에 달려 있습니다.
서비스 :
목록의 경우 :
- http://www.maxmind.com/app/geoip_country (기준 바와 같이 오리온 )
RIR에서 목록을 다운로드하여 직접 롤링 할 수 있습니다.
다음은 공개 API가있는 멋진 무료 서비스입니다. http://www.hostip.info/use.html
ipinfodb 는 IP에 대한 무료 데이터베이스 및 API를 국가에 제공하거나 그 반대로 제공합니다. 그들은 MaxMind의 무료 데이터를 사용합니다. 데이터는 매달 업데이트되며 적절한 정확성을 갖춘 훌륭한 무료 대안입니다.
hostip.info 사이트가 얼마나 정확한지 모르겠습니다. 방금 그 사이트를 방문했는데 우리 나라가 캐나다라고보고했습니다. 저는 미국에 있으며 사무실에서 사용하는 ISP는 미국에서만 운영됩니다. 추측을 수정할 수는 있지만이 서비스를 사용하여 국가별로 웹 사이트 방문자를 추적하는 경우 데이터가 올바른지 알 수있는 방법이 없습니다. 물론 나는 단지 하나의 데이터 포인트 일뿐입니다. .csv 파일 인 GeoLite 국가 데이터베이스를 다운로드했는데 내 IP 주소가 US로 올바르게 식별되었습니다.
MaxMind 제품 라인 (유료 또는 무료)의 또 다른 이점은 데이터가 있고 다른 시스템에 웹 서비스를 호출 할 때 성능 저하가 발생하지 않는다는 것입니다.
가장 정확한 것은 Digital Elements NetAcuity입니다 ... 무료는 아니지만 대부분의 시간 동안 지불 한만큼 얻을 수 있습니다 .... Digital Element
Google의 clientlocation 반환 ( 내 예 )
latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
location = "IP location: " + getFormattedLocation();
document.getElementById("location").innerHTML = location;
이 질문에 제공된 솔루션을 사용할 수 있습니다 .
그러나 2 자리 국가 코드를 반환합니다.
이 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];?>
이를 위해 내 서비스 인 http://ipinfo.io를 사용할 수 있습니다 . API는 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
}
국가 코드 뒤에있는 경우 URL에 / country를 추가하기 만하면됩니다.
$ curl ipinfo.io/8.8.8.8/country
US
다음은 사용할 수있는 일반적인 PHP 함수입니다.
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
이 예제에서는 IP 8.8.8.8을 사용했지만 사용자의 IP에 대한 세부 정보를 원한다면 $_SERVER['REMOTE_ADDR']대신 전달하십시오 . 자세한 내용은 http://ipinfo.io/developers 에서 확인할 수 있습니다.
http://www.mmtutorialvault.com/php-ip-to-country-function/ 에서 ipToCountry ($ ip) 함수를 사용 하십시오.
이 작업을 수행하는 웹 서비스 API를 다음과 같이 사용할 수 있습니다.
see example of service: http://ip-api.com and usage: http://whatmyip.info
ip 주소에서 여러 데이터 포인트를 제공하는 ipdata.co 를 참조하십시오 .
API는 매우 빠르며 10 개의 글로벌 엔드 포인트가 매일 8 억 이상의 호출을 처리 할 수 있습니다.
다음은 컬의 예입니다.
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
}
}⏎
무료 IP2Location LITE 데이터베이스를 사용해 볼 수 있습니다.
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;
데이터를 가져 오려면
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;
MySQL을 쿼리하는 PHP 코드
<?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);
}
}
?>
참고 URL : https://stackoverflow.com/questions/1033/how-to-get-the-country-according-to-a-certain-ip
'IT Share you' 카테고리의 다른 글
| Python 로깅-가져온 모듈에서 로깅 비활성화 (0) | 2020.12.11 |
|---|---|
| AWS 자격 증명을 Docker 컨테이너에 전달하는 가장 좋은 방법은 무엇입니까? (0) | 2020.12.11 |
| API 테스트를위한 cURL 용 GUI 프런트 엔드 (0) | 2020.12.11 |
| 하나의 XAML 스타일에 대해 여러 TargetType을 정의 할 수 있습니까? (0) | 2020.12.11 |
| Emacs 구문 강조 색상 변경 (0) | 2020.12.11 |