IP Geolocation API的实现

概述

随着逐渐深入人心的互联网思维,越来越多的个人网站及公共论坛被主流搜索引擎收录。精确现IP地址归属地经纬度查询,显示请求者所属的国家/地区/城市以及所属的网络运营商ISP或者自治系统号ASN(Autonomous System Number)以此用于数据分析,成为越来越多人的需求。

本文所述IP Geolocation API集成自ipify.org的免费服务,Free Plan的请求限制是每月不高于一千次,足以应付绝大多数个人业务的轻量级业务需求。

下面给出一些常用的IP归属地公共API接口:

https://pv.sohu.com/cityjson?ie=utf-8
https://www.myip.com/api-docs/
https://api.myip.com

Javascript

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    var ip = "8.8.8.8";
    var api_key = "your_api_key";
    $(function () {
       $.ajax({
           url: "https://geo.ipify.org/api/v1",
           dataType: "jsonp",
           data: {apiKey: api_key, ipAddress: ip},
           success: function(data) {
               $("body").append("<pre>"+ JSON.stringify(data,"",2)+"</pre>");
           }
       });
    });
</script>

Java

public class GeoipifyAPIQuery {
    public static void main(String[]args){
        String IP = "8.8.8.8";
        String API_KEY = "your_api_key";
        String API_URL = "https://geo.ipify.org/api/v1?";
        String url = API_URL + "&apiKey=" + API_KEY + 
                     "&ipAddress=" + IP;
        try (java.util.Scanner s = 
            new java.util.Scanner(new java.net.URL(url).openStream())) {
            System.out.println(s.useDelimiter("\\A").next());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Python

try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

ip = '8.8.8.8'
api_key = 'your_api_key'
api_url = 'https://geo.ipify.org/api/v1?'

url = api_url + 'apiKey=' + api_key + '&ipAddress=' + ip

print(urlopen(url).read().decode('utf8'))

PHP

<?php
/**
*2020-01-30
*Twilight Summer
*/
header('Content-Type: text/html; charset=UTF-8');
//开启跨域Ajax支持
header('Access-Control-Allow-Origin:*');
//初始化资源文件

// $url='https://api.myip.com';
$api_url = 'https://geo.ipify.org/api/v1';
$api_key = '************';
$ip =summer_getip();

$url_total="{$api_url}?apiKey={$api_key}&ipAddress={$ip}";

$info = file_get_contents($url_total);

/**
*获取当前请求IP
*排除CDN干扰
*/
function summer_getip(){
 if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
   $ip = getenv("HTTP_CLIENT_IP");
  } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
   $ip = getenv("HTTP_X_FORWARDED_FOR");
  } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) {
   $ip = getenv("REMOTE_ADDR");
  } else  if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
   $ip = $_SERVER['REMOTE_ADDR'];
  } else {
   $ip = "unknown";
  }
 return $ip;
}

//echo $ip;


//判断输出类型
if ($encode == 'javascript' || $encode == 'js')
{
    echo 'function getIP(){document.write("',trim($info),'");}';
}
else
{
    echo trim($info);
}

鸣谢: PHP一个页面根据传的不同值显示不同的内容

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注