如何从IP列表中找到最接近的IP?

时间:2019-05-13 13:11:37

标签: javascript networking ip protocols

我想知道是否可能

我有一个给定的 IP,例如: 191.184.222.43 (公共ipv4)

我还有其他IP地址的Loong列表,例如:

[ip1,ip2,ip3,ip4 ...等]

现在,我必须找到列表中哪个IP(物理上)最接近我的给定 IP( 191.184.222.43

有可能吗?还是我有不同的想法

1 个答案:

答案 0 :(得分:1)

https://ipstack.com/上有许多API可以完成一个示例。它基于IP进行地理位置定位,并且通过一些解析,您可以轻松实现这一目标!

ipstack.com

示例代码:

// set endpoint and your access key
var ip = '134.201.250.155'
var access_key = 'YOUR_ACCESS_KEY';

// get the API result via jQuery.ajax
$.ajax({
    url: 'https://api.ipstack.com/' + ip + '?access_key=' + access_key,   
    dataType: 'jsonp',
    success: function(json) {

        // output the "capital" object inside "location"
        alert(json.location.capital);

    }
});

示例输出(JSON):

[
  {
    "ip": "134.201.250.155",
    "type": "ipv4",
    "continent_code": "NA",
    "continent_name": "North America",
    "country_code": "US",
    "country_name": "United States",
    "region_code": "CA",
    "region_name": "California",
    "city": "Los Angeles",
    "zip": "90013",
    "latitude": 34.0453,
    "longitude": -118.2413,
    "location": { ... },
    "time_zone": { ... },
    "currency": { ... },
    "connection": { ... },
  }
]
相关问题