当前位置:  开发笔记 > 编程语言 > 正文

如何使用JavaScript获取客户端的IP地址?

如何解决《如何使用JavaScript获取客户端的IP地址?》经验,为你挑选了29个好方法。

我需要以某种方式使用JavaScript检索客户端的IP地址; 没有服务器端代码,甚至没有SSI.

但是,我并不反对使用免费的第三方脚本/服务.



1> thdoan..:

我会使用一个可以返回JSON的Web服务(与jQuery一起使事情变得更简单).以下是我能找到的所有免费主动 IP查找服务以及它们返回的信息.如果您知道更多,请添加评论我会更新此答案.


DB-IP

试试看: http ://api.db-ip.com/addrinfo?api_key = < 你的api密钥 >&addr = < ip address >

返回:

{
  "address": "116.12.250.1",
  "country": "SG",
  "stateprov": "Central Singapore",
  "city": "Singapore"
}

限制:

每天2,500个请求

不支持JSONP回调

需要IP地址参数

需要电子邮件地址才能获取API密钥

没有SSL(https)与免费计划


Geobytes

试试看: http ://gd.geobytes.com/GetCityDetails

$.getJSON('http://gd.geobytes.com/GetCityDetails?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

返回:

{
  "geobytesforwarderfor": "",
  "geobytesremoteip": "116.12.250.1",
  "geobytesipaddress": "116.12.250.1",
  "geobytescertainty": "99",
  "geobytesinternet": "SA",
  "geobytescountry": "Saudi Arabia",
  "geobytesregionlocationcode": "SASH",
  "geobytesregion": "Ash Sharqiyah",
  "geobytescode": "SH",
  "geobyteslocationcode": "SASHJUBA",
  "geobytescity": "Jubail",
  "geobytescityid": "13793",
  "geobytesfqcn": "Jubail, SH, Saudi Arabia",
  "geobyteslatitude": "27.004999",
  "geobyteslongitude": "49.660999",
  "geobytescapital": "Riyadh ",
  "geobytestimezone": "+03:00",
  "geobytesnationalitysingular": "Saudi Arabian ",
  "geobytespopulation": "22757092",
  "geobytesnationalityplural": "Saudis",
  "geobytesmapreference": "Middle East ",
  "geobytescurrency": "Saudi Riyal",
  "geobytescurrencycode": "SAR",
  "geobytestitle": "Saudi Arabia"
}

限制:

每小时16,384个请求

没有SSL(https)与免费计划

可以返回错误的位置(我在新加坡,而不是沙特阿拉伯)


GeoIPLookup.io

试试吧: https ://json.geoiplookup.io/api

$.getJSON('https://json.geoiplookup.io/api?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

返回:

{
    "ip": "116.12.250.1",
    "isp": "SGPOST",
    "org": "Singapore Post Ltd",
    "hostname": "116.12.250.1",
    "longitude": "103.807",
    "latitude": "1.29209",
    "postal_code": "",
    "city": "Singapore",
    "country_code": "SG",
    "country_name": "Singapore",
    "continent_code": "AS",
    "region": "Central Singapore",
    "district": "",
    "timezone_name": "Asia\/Singapore",
    "connection_type": "",
    "asn": "AS3758 SingNet",
    "currency_code": "SGD",
    "currency_name": "Singapore Dollar",
    "success": true
}

限制:

未知


geoPlugin

试试看: http ://www.geoplugin.net/json.gp

$.getJSON('http://www.geoplugin.net/json.gp?jsoncallback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

返回:

{
  "geoplugin_request": "116.12.250.1",
  "geoplugin_status": 200,
  "geoplugin_credit": "Some of the returned data includes GeoLite data created by MaxMind, available from http://www.maxmind.com.",
  "geoplugin_city": "Singapore",
  "geoplugin_region": "Singapore (general)",
  "geoplugin_areaCode": "0",
  "geoplugin_dmaCode": "0",
  "geoplugin_countryCode": "SG",
  "geoplugin_countryName": "Singapore",
  "geoplugin_continentCode": "AS",
  "geoplugin_latitude": "1.2931",
  "geoplugin_longitude": "103.855797",
  "geoplugin_regionCode": "00",
  "geoplugin_regionName": "Singapore (general)",
  "geoplugin_currencyCode": "SGD",
  "geoplugin_currencySymbol": "$",
  "geoplugin_currencySymbol_UTF8": "$",
  "geoplugin_currencyConverter": 1.4239
}

限制:

每分钟120个请求

没有SSL(https)与免费计划


黑客目标

试试看: https ://api.hackertarget.com/geoip/?q = < ip address >

返回:

IP Address: 116.12.250.1
Country: SG
State: N/A
City: Singapore
Latitude: 1.293100
Longitude: 103.855797

限制:

每天50个请求

不支持JSONP回调

需要IP地址参数

返回纯文本


ipapi.co

试试吧: https ://ipapi.co/json/

$.getJSON('https://ipapi.co/json/', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

返回:

{
  "ip": "116.12.250.1",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "country": "SG",
  "country_name": "Singapore",
  "postal": null,
  "latitude": 1.2855,
  "longitude": 103.8565,
  "timezone": "Asia/Singapore"
}

限制:

每天1,000个请求

需要SSL(https)


IP-API.com

试试看: http ://ip-api.com/json

$.getJSON('http://ip-api.com/json?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

返回:

{
  "as": "AS3758 SingNet",
  "city": "Singapore",
  "country": "Singapore",
  "countryCode": "SG",
  "isp": "SingNet Pte Ltd",
  "lat": 1.2931,
  "lon": 103.8558,
  "org": "Singapore Telecommunications",
  "query": "116.12.250.1",
  "region": "01",
  "regionName": "Central Singapore Community Development Council",
  "status": "success",
  "timezone": "Asia/Singapore",
  "zip": ""
}

限制:

每分钟150个请求

没有SSL(https)与免费计划


Ipdata.co

试试吧: https ://api.ipdata.co

$.getJSON('https://api.ipdata.co', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

返回:

{
  "ip": "116.12.250.1",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "region_code": "01",
  "country_name": "Singapore",
  "country_code": "SG",
  "continent_name": "Asia",
  "continent_code": "AS",
  "latitude": 1.2931,
  "longitude": 103.8558,
  "asn": "AS3758",
  "organisation": "SingNet",
  "postal": "",
  "calling_code": "65",
  "flag": "https://ipdata.co/flags/sg.png",
  "emoji_flag": "\ud83c\uddf8\ud83c\uddec",
  "emoji_unicode": "U+1F1F8 U+1F1EC",
  "is_eu": false,
  "languages": [
    {
      "name": "English",
      "native": "English"
    },
    {
      "name": "Malay",
      "native": "Bahasa Melayu"
    },
    {
      "name": "Tamil",
      "native": "\u0ba4\u0bae\u0bbf\u0bb4\u0bcd"
    },
    {
      "name": "Chinese",
      "native": "\u4e2d\u6587"
    }
  ],
  "currency": {
    "name": "Singapore Dollar",
    "code": "SGD",
    "symbol": "S$",
    "native": "$",
    "plural": "Singapore dollars"
  },
  "time_zone": {
    "name": "Asia/Singapore",
    "abbr": "+08",
    "offset": "+0800",
    "is_dst": false,
    "current_time": "2018-05-09T12:28:49.183674+08:00"
  },
  "threat": {
    "is_tor": false,
    "is_proxy": false,
    "is_anonymous": false,
    "is_known_attacker": false,
    "is_known_abuser": false,
    "is_threat": false,
    "is_bogon": false
  }
}

限制:

每天1,500个请求

需要电子邮件地址才能获取API密钥

需要SSL(https)


IP查找

试试看: https ://ipfind.co/me?auuth = < 你的api密钥 >

$.getJSON('https://ipfind.co/me?auth=', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

返回:

{
  "ip_address": "116.12.250.1",
  "country": "Singapore",
  "country_code": "SG",
  "continent": "Asia",
  "continent_code": "AS",
  "city": "Singapore",
  "county": null,
  "region": "Central Singapore",
  "region_code": "01",
  "timezone": "Asia/Singapore",
  "owner": null,
  "longitude": 103.8565,
  "latitude": 1.2855,
  "currency": "SGD",
  "languages": [
    "cmn",
    "en-SG",
    "ms-SG",
    "ta-SG",
    "zh-SG"
  ]
}

限制:

300 requests per day

Requires registration to get your API key


ipgeolocation

Try it: https://api.ipgeolocation.io/ipgeo?apiKey=<your api key>

$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "continent_code": "AS",
  "continent_name": "Asia",
  "country_code2": "SG",
  "country_code3": "SGP",
  "country_name": "Singapore",
  "country_capital": "Singapore",
  "state_prov": "Central Singapore",
  "district": "",
  "city": "Singapore",
  "zipcode": "",
  "latitude": "1.29209",
  "longitude": "103.807",
  "is_eu": false,
  "calling_code": "+65",
  "country_tld": ".sg",
  "languages": "cmn,en-SG,ms-SG,ta-SG,zh-SG",
  "country_flag": "https://ipgeolocation.io/static/flags/sg_64.png",
  "isp": "SGPOST",
  "connection_type": "",
  "organization": "Singapore Post Ltd",
  "geoname_id": "1880252",
  "currency": {
    "name": "Dollar",
    "code": "SGD"
  },
  "time_zone": {
    "name": "Asia/Singapore",
    "offset": 8,
    "is_dst": false,
    "current_time": "2018-06-12 09:06:49.028+0800"
  }
}

Limitations:

50,000 requests per month

Requires registration to get your API key


ipify

Try it: https://api.ipify.org/?format=json

$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1"
}

Limitations:

None


IPInfoDB

Try it: https://api.ipinfodb.com/v3/ip-city/?key=<your api key>&format=json

$.getJSON('https://api.ipinfodb.com/v3/ip-city/?key=&format=json&callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "statusCode": "OK",
  "statusMessage": "",
  "ipAddress": "116.12.250.1",
  "countryCode": "SG",
  "countryName": "Singapore",
  "regionName": "Singapore",
  "cityName": "Singapore",
  "zipCode": "048941",
  "latitude": "1.28967",
  "longitude": "103.85",
  "timeZone": "+08:00"
}

Limitations:

Two requests per second

Requires registration to get your API key


ipinfo.io

Try it: https://ipinfo.io/json

$.getJSON('https://ipinfo.io/json', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "hostname": "No Hostname",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "country": "SG",
  "loc": "1.2931,103.8558",
  "org": "AS3758 SingNet"
}

Limitations:

1,000 requests per day


ipstack (formerly freegeoip.net)

Try it: http://api.ipstack.com/<ip address>?access_key=

$.getJSON('https://api.ipregistry.co/?key=', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip" : "116.12.250.1",
  "type" : "IPv4",
  "hostname" : null,
  "carrier" : {
    "name" : null,
    "mcc" : null,
    "mnc" : null
  },
  "connection" : {
    "asn" : 3758,
    "domain" : "singnet.com.sg",
    "organization" : "SingNet Pte Ltd",
    "type" : "isp"
  },
  "currency" : {
    "code" : "SGD",
    "name" : "Singapore Dollar",
    "plural" : "Singapore dollars",
    "symbol" : "SGD",
    "symbol_native" : "SGD",
    "format" : {
      "negative" : {
        "prefix" : "-SGD",
        "suffix" : ""
      },
      "positive" : {
        "prefix" : "SGD",
        "suffix" : ""
      }
    }
  },
  "location" : {
    "continent" : {
      "code" : "AS",
      "name" : "Asia"
    },
    "country" : {
      "area" : 692.0,
      "borders" : [ ],
      "calling_code" : "65",
      "capital" : "Singapore",
      "code" : "SG",
      "name" : "Singapore",
      "population" : 5638676,
      "population_density" : 8148.38,
      "flag" : {
        "emoji" : "",
        "emoji_unicode" : "U+1F1F8 U+1F1EC",
        "emojitwo" : "https://cdn.ipregistry.co/flags/emojitwo/sg.svg",
        "noto" : "https://cdn.ipregistry.co/flags/noto/sg.png",
        "twemoji" : "https://cdn.ipregistry.co/flags/twemoji/sg.svg",
        "wikimedia" : "https://cdn.ipregistry.co/flags/wikimedia/sg.svg"
      },
      "languages" : [ {
        "code" : "cmn",
        "name" : "cmn",
        "native" : "cmn"
      }, {
        "code" : "en",
        "name" : "English",
        "native" : "English"
      }, {
        "code" : "ms",
        "name" : "Malay",
        "native" : "Melayu"
      }, {
        "code" : "ta",
        "name" : "Tamil",
        "native" : "?????"
      }, {
        "code" : "zh",
        "name" : "Chinese",
        "native" : "??"
      } ],
      "tld" : ".sg"
    },
    "region" : {
      "code" : null,
      "name" : "Singapore"
    },
    "city" : "Singapore",
    "postal" : "96534",
    "latitude" : 1.28967,
    "longitude" : 103.85007,
    "language" : {
      "code" : "cmn",
      "name" : "cmn",
      "native" : "cmn"
    },
    "in_eu" : false
  },
  "security" : {
    "is_bogon" : false,
    "is_cloud_provider" : false,
    "is_tor" : false,
    "is_tor_exit" : false,
    "is_proxy" : false,
    "is_anonymous" : false,
    "is_abuser" : false,
    "is_attacker" : false,
    "is_threat" : false
  },
  "time_zone" : {
    "id" : "Asia/Singapore",
    "abbreviation" : "SGT",
    "current_time" : "2019-09-29T23:13:32+08:00",
    "name" : "Singapore Standard Time",
    "offset" : 28800,
    "in_daylight_saving" : false
  }
}

Limitations:

10,000 requests per month

Requires IP address parameter

Requires registration to get your API key

No SSL (https) with the free plan


jsonip.com

Try it: https://jsonip.com

$.getJSON('http://api.ipstack.com/?access_key=', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
    "ip": "116.12.250.1",
    "type": "ipv4",
    "continent_code": "AS",
    "continent_name": "Asia",
    "country_code": "SG",
    "country_name": "Singapore",
    "region_code": "01",
    "region_name": "Central Singapore Community Development Council",
    "city": "Singapore",
    "zip": null,
    "latitude": 1.2931,
    "longitude": 103.8558,
    "location": {
        "geoname_id": 1880252,
        "capital": "Singapore",
        "languages": [{
            "code": "en",
            "name": "English",
            "native": "English"
        },
        {
            "code": "ms",
            "name": "Malay",
            "native": "Bahasa Melayu"
        },
        {
            "code": "ta",
            "name": "Tamil",
            "native": "\u0ba4\u0bae\u0bbf\u0bb4\u0bcd"
        },
        {
            "code": "zh",
            "name": "Chinese",
            "native": "\u4e2d\u6587"
        }],
        "country_flag": "http:\/\/assets.ipstack.com\/flags\/sg.svg",
        "country_flag_emoji": "\ud83c\uddf8\ud83c\uddec",
        "country_flag_emoji_unicode": "U+1F1F8 U+1F1EC",
        "calling_code": "65",
        "is_eu": false
    }
}

Limitations:

The response includes upsell and politics


JSON Test

Try it: http://ip.jsontest.com/

$.getJSON('https://jsonip.com/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "about": "/about",
  "Pro!": "http://getjsonip.com",
  "reject-fascism": "Liberal America will prevail"
}

Limitations:

No SSL (https)

Goes down a lot (over quota), so I wouldn't use it for production

Returns IPv6 address if you have one, which may not be what you want


Nekudo

Try it: https://geoip.nekudo.com/api

$.getJSON('http://ip.jsontest.com/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1"
}

Limitations:

Blocked by ad blockers using the EasyPrivacy list


Stupid Web Tools

Try it: http://www.stupidwebtools.com/api/my_ip.json

$.getJSON('https://geoip.nekudo.com/api', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "city": "Singapore",
  "country": {
    "name": "Singapore",
    "code": "SG"
  },
  "location": {
    "accuracy_radius": 50,
    "latitude": 1.2855,
    "longitude": 103.8565,
    "time_zone": "Asia/Singapore"
  },
  "ip": "116.12.250.1"
}

Limitations:

No SSL (https)


Keep in mind that since these are all free services, your mileage may vary in terms of exceeding quota and uptime, and who knows when/if they will be taken offline down the road (exhibit A: Telize). Most of these services also offer a paid tier in case you want more features like SSL support.

Also, as skobaljic noted in the comments below, the request quotas are mostly academic since this is happening client-side and most end users will never exceed the quota.

UPDATES

2/1/2016: Removed Telize (no longer offers free plan)

4/18/2016: Removed freegeoip.net (out of service)

4/26/2016: Added DB-IP

4/26/2016: Added Hacker Target

7/6/2016: Reinstated freegeoip.net

7/6/2016: Removed ip-json.rhcloud.com (dead link)

12/21/2016: Removed Hacker Target (out of service)

2/10/2017: Added Nekudo

4/20/2017: Added ipapi.co (thanks Ahmad Awais)

4/24/2017: Reinstated Hacker Target

4/24/2017: Removed Snoopi.io (out of service)

7/16/2017: Added IP Find (thanks JordanC)

7/16/2017: Updated limitation for free plans that don't support SSL

9/25/2017: Added Stupid Web Tools (thanks Cœur)

3/16/2018: Added Ipdata.co (thanks Jonathan)

4/14/2018: Renamed freegeoip.net to ipstack (thanks MA-Maddin)

4/16/2018: Added GeoIPLookup.io (thanks Rob Waa)

6/11/2018: Added ipgeolocation (thanks Ejaz Ahmed)


其中每一个都使用服务器端代码.
@AfolabiOlaoluwaAkinwumi你可以尝试这样的事情:`$ .getJSON('// freegeoip.net/json/?callback=?',function(data){if(!data ||!data.ip)alert('IP not发现');}).失败(function(){alert('$.getJSON()request failed');});`
@JohnWeisz是的,但是如果OP仅仅意味着他们只能更新页面而不能在服务器端做任何事情(问题尚不清楚),那么这些选项可以很好地回答问题。

2> mido..:

更新:我一直想创建一个min/uglified版本的代码,所以这是一个ES6 Promise代码:

var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})

/*Usage example*/
findIP.then(ip => document.write('your ip: ', ip)).catch(e => console.error(e))


3> Chad Grant..:

您可以通过服务器端使用JSONP进行转发

在谷歌搜索找到一个,在这里找到它可以使用客户端Javascript执行DNS查找(IP地址的主机名)?




注意:截至2015年11月15日, telize.com API已永久关闭.


虽然我很欣赏这个片段,但我认为加载JavaScript文本内容并通过函数评估它是一个严重的安全风险.如果响应的内容发生变化并且所有100多人投票支持并且可能使用该片段最终调用具有可能不安全内容的函数,该怎么办?如果它是一个JSON字符串我只会使用它.
`配额错误此应用程序暂时超过其服务配额.请稍后再试
这不是一个好的答案,因为它涉及服务器端请求.这个问题清楚地说明了"纯粹的javascript".
"NetworkError:404 Not Found - http://jsonip.appspot.com/?callback=getip"
该服务现已停止.
Micah,没有办法用纯javascript获取IP地址.我建议你做一些关于NAT的阅读以及它是如何工作的.您需要一台服务器来回复您的Internet IP地址

4> Shog9..:

这里的大多数答案"解决"服务器端代码的需求...击中别人的服务器.这是一种完全有效的技术,除非您确实需要获取IP地址而不需要服务器.

传统上,如果没有某种插件,这是不可能的(即使这样,如果你在NAT路由器后面,你可能会得到错误的 IP地址),但随着WebRTC的出现,它实际上可以做到这一点. .如果你的目标是支持的WebRTC的浏览器(目前为:火狐,Chrome和Opera).

有关如何使用WebRTC检索有用的客户端IP地址的详细信息,请阅读mido的答案.


@oscar:这似乎是他在答案中提到的同一技术(JSONP返回的服务器可见IP).这与OP的"无服务器端代码"要求不符.但是,如果您忽略该要求,这是实现它的一种方法.

5> 小智..:

你可以对hostip.info或类似的服务进行ajax调用......

function myIP() {
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.open("GET","http://api.hostip.info/get_html.php",false);
    xmlhttp.send();

    hostipInfo = xmlhttp.responseText.split("\n");

    for (i=0; hostipInfo.length >= i; i++) {
        ipAddress = hostipInfo[i].split(":");
        if ( ipAddress[0] == "IP" ) return ipAddress[1];
    }

    return false;
}

作为奖励,地理定位信息在同一个呼叫中返回.


`api.hostip.info`无法解决.
您还可以使用http://api.hostip.info/get_json.php获取JSON表示,然后使用浏览器函数jQuery或Prototype解析JSON.
"http://api.hostip.info/get_html.php"有任何请求限制吗?我在哪里可以看到这个api细节

6> Sridhar R..:
试试这个
$.get("http://ipinfo.io", function(response) {
    alert(response.ip);
}, "jsonp");

要么

$(document).ready(function () {
    $.getJSON("http://jsonip.com/?callback=?", function (data) {
        console.log(data);
        alert(data.ip);
    });
});

小提琴



7> SteveShaffer..:

你不能.你必须问一个服务器.


但它确实有,对吗?我的意思是,如果答案只是"不,你不能",那么我认为这是一个更正确的答案,而不是目前支持的"在这里,使用这个随机的appspot应用程序",这似乎是一个危险的答案,在最重要的.
IMO这是正确的答案,应该被接受.问题具体说"没有服务器端代码".
这并没有提供问题的答案.要对作者进行批评或要求澄清,请在帖子下方留言.
@matthewwithanm我完全同意。我正在浏览所有答案,以查看是否有人说过这句话-并准备自己提供答案。所有获得高度评价的答案,虽然内容丰富,但都回答了一个不同的问题。提出问题:“我需要以某种方式使用纯JavaScript提取客户端的IP地址;没有服务器端代码,甚至没有SSI。” 实际上,这个答案是正确的答案。沙盒浏览器的Javascript无法执行此操作(无论NAT或代理如何)。如果要接受其他答案之一,则应更改该问题。

8> FloatingRock..:
不要再犹豫了

查看http://www.ipify.org/

根据他们:

您可以无限制地使用它(即使您每分钟执行数百万次请求).

ipify是完全开源的(查看GitHub存储库).

这是一个有效的JS示例(而不是想知道为什么这个答案的票数很少,请亲自尝试看看它的实际效果):



太懒了复制/粘贴?我喜欢.这是一个演示

太懒了点击? :O

注意:在运行演示之前关闭Adblock Plus/uBlock&co ..否则,它将无效.

我与IPify团队无关.我认为有人会为一般商品提供这样的服务真是太酷了.


最好的部分是这来自"https",而我对http IP助手的调用会被阻止,因为它们"不安全".

9> Ben Dowling..:

您可以使用我的服务http://ipinfo.io,它将为您提供客户端IP,主机名,地理位置信息和网络所有者.这是一个记录IP的简单示例:

$.get("http://ipinfo.io", function(response) {
    console.log(response.ip);
}, "jsonp");

这是一个更详细的JSFiddle示例,它还打印出完整的响应信息,因此您可以看到所有可用的详细信息:http://jsfiddle.net/zK5FN/2/



10> 小智..:

在您的网页中包含此代码:

更多doc 在这里



11> user4951..:

我想说乍得和马耳他有很好的答案.然而,他们很复杂.所以我建议我通过国家/地区插件从广告中找到此代码



没有ajax.只是简单的javascripts.:d

如果你去http://j.maxmind.com/app/geoip.js,你会看到它包含

function geoip_country_code() { return 'ID'; }
function geoip_country_name() { return 'Indonesia'; }
function geoip_city()         { return 'Jakarta'; }
function geoip_region()       { return '04'; }
function geoip_region_name()  { return 'Jakarta Raya'; }
function geoip_latitude()     { return '-6.1744'; }
function geoip_longitude()    { return '106.8294'; }
function geoip_postal_code()  { return ''; }
function geoip_area_code()    { return ''; }
function geoip_metro_code()   { return ''; }

它还没有真正回答这个问题,因为

http://j.maxmind.com/app/geoip.js不包含IP(虽然我打赌它使用IP来获取国家).

但是制作一个像PhP这样的PhP脚本是如此容易

function visitorsIP()   { return '123.123.123.123'; }

做那个.穿上http://yourdomain.com/yourip.php.

然后做


问题特别提到不要使用第三方脚本.没有其他办法.Javascript无法知道您的IP.但是其他可以通过javascript访问的服务器可以正常工作而没有问题.


从远程服务器加载JavaScript并调用具有未知内容的函数对我来说似乎是一个巨大的安全风险(如果函数内容发生变化会怎样?).我宁愿选择解析JSON响应.
错误404:找不到对象

12> BRebey..:

这个问题有两种解释.大多数人将"客户端IP"解释为Web服务器在LAN外部和Internet上看到的公共IP地址.但是,在大多数情况下,这不是客户端计算机的IP地址

我需要运行托管我的JavaScript软件的浏览器的计算机的真实IP地址(这几乎总是局域网上的本地IP地址,这是NAT层的背后).

Mido在上面发布了一个奇妙的答案,这似乎是真正提供客户端IP地址的唯一答案.

谢谢你,Mido!

但是,所呈现的功能是异步运行的.我需要在我的代码中实际使用IP地址,并且使用异步解决方案,我可能会在检索/学习/存储之前尝试使用IP地址.在使用它们之前,我必须能够等待结果到达.

这是Mido功能的"Waitable"版本.我希望它可以帮助别人:

function findIP(onNewIP) { //  onNewIp - your listener function for new IPs
    var promise = new Promise(function (resolve, reject) {
        try {
            var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
            var pc = new myPeerConnection({ iceServers: [] }),
                noop = function () { },
                localIPs = {},
                ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
                key;
            function ipIterate(ip) {
                if (!localIPs[ip]) onNewIP(ip);
                localIPs[ip] = true;
            }
            pc.createDataChannel(""); //create a bogus data channel
            pc.createOffer(function (sdp) {
                sdp.sdp.split('\n').forEach(function (line) {
                    if (line.indexOf('candidate') < 0) return;
                    line.match(ipRegex).forEach(ipIterate);
                });
                pc.setLocalDescription(sdp, noop, noop);
            }, noop); // create offer and set local description

            pc.onicecandidate = function (ice) { //listen for candidate events
                if (ice && ice.candidate && ice.candidate.candidate && ice.candidate.candidate.match(ipRegex)) {
                    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
                }
                resolve("FindIPsDone");
                return;
            };
        }
        catch (ex) {
            reject(Error(ex));
        }
    });// New Promise(...{ ... });
    return promise;
};

//This is the callback that gets run for each IP address found
function foundNewIP(ip) {
    if (typeof window.ipAddress === 'undefined')
    {
        window.ipAddress = ip;
    }
    else
    {
        window.ipAddress += " - " + ip;
    }
}

//This is How to use the Waitable findIP function, and react to the
//results arriving
var ipWaitObject = findIP(foundNewIP);        // Puts found IP(s) in window.ipAddress
ipWaitObject.then(
    function (result) {
        alert ("IP(s) Found.  Result: '" + result + "'. You can use them now: " + window.ipAddress)
    },
    function (err) {
        alert ("IP(s) NOT Found.  FAILED!  " + err)
    }
);


 

   

Demo "Waitable" Client IP Retrieval using WebRTC



13> Cyril Gupta..:

好吧,我对这个问题很离题,但今天我有类似的需求,虽然我无法使用Javascript从客户端找到ID,但我做了以下操作.

在服务器端: -

<%= Request.UserHostAddress %>

使用Javascript

var ip = $get("uip").innerHTML;

我正在使用ASP.Net Ajax,但您可以使用getElementById而不是$ get().

发生了什么,我在页面上有一个隐藏的div元素,用户的IP从服务器呈现.比Javascript我只是加载该值.

对于像你这样有类似要求的人来说这可能会有所帮助(就像我一样,但我没想到这一点).

干杯!


-1:OP特别提到"没有服务器端代码",但你使用了一些C#.
输出` UserInfo.getInfo(function(data) { alert(data.ip_address); }, function(err) { // Do something with the error });

您还可以使用requirejs加载脚本.

它将为您提供访问者的IP地址,以及其位置(国家,城市等)的一些数据.它基于maxmind geoip数据库.

免责声明:我写了这个库



19> Ken Le..:

Javascript/jQuery获取客户的IP地址和位置(国家,城市)

您只需要将带有"src"链接的标记嵌入到服务器中.服务器将返回"codehelper_ip"作为Object/JSON,您可以立即使用它.

// First, embed this script in your head or at bottom of the page.

// You can use it

有关Javascript的详细信息,请检测Real IP Address Plus国家/地区

如果您使用的是jquery,可以尝试:

console.log(codehelper_ip); 

它将显示有关返回对象的更多信息.

如果你想要回调函数,请试试这个:

// First, embed this script in your head or at bottom of the page.

// You can use it



20> 小智..:

Appspot.com回调的服务不可用.ipinfo.io似乎正在运作.

我做了一个额外的步骤,并使用AngularJS检索所有地理信息.(感谢里卡多)看看吧.

工作页面:http://www.orangecountyseomarketing.com/projects/_ip_angularjs.html



21> Sarel Botha..:

获取客户端计算机的IP地址并不是一种可靠的方法.

这经历了一些可能性.如果用户具有多个接口,则使用Java的代码将中断.

http://nanoagent.blogspot.com/2006/09/how-to-find-evaluate-remoteaddrclients.html

从这里查看其他答案,听起来您可能想要获取客户端的公共IP地址,这可能是他们用来连接到互联网的路由器的地址.这里有很多其他答案都在谈论这个问题.我建议创建和托管您自己的服务器端页面,以接收请求并使用IP地址进行响应,而不是依赖于可能会或可能不会继续工作的其他人的服务.



22> Martijn..:

如果你要包含一个文件,你可以做一个简单的ajax get:

function ip_callback() {
    $.get("ajax.getIp.php",function(data){ return data; }
}

ajax.getIp.php会是这样:




23> Tim Penner..:

我非常喜欢,api.ipify.org因为它支持HTTP和HTTPS.

以下是api.ipify.org使用jQuery 获取IP的一些示例.

通过HTTPS的JSON格式

https://api.ipify.org?format=json

$.getJSON("https://api.ipify.org/?format=json", function(e) {
    alert(e.ip);
});


24> Jonathan..:

使用ipdata.co.

API还提供地理定位数据,并拥有10个全局端点,每个端点每天可处理超过80000个请求!

这个答案使用的"测试"API密钥非常有限,仅用于测试几个调用.注册您自己的免费API密钥,每天最多可获得1500个请求以进行开发.

$.get("https://api.ipdata.co?api-key=test", function (response) {
    $("#response").html(response.ip);
}, "jsonp");



25> TARKUS..:

我想提供一种方法,当我想在html页面中存储信息时,我会使用很多方法,并希望我的javascript读取信息而不必将参数传递给javascript.当您的脚本在外部引用而不是内联时,这尤其有用.

但是,它不符合"无服务器端脚本"的标准.但是,如果您可以在html中包含服务器端脚本,请执行以下操作:

在html页面的底部,在最终正文标记的正上方创建隐藏的标签元素.

您的标签将如下所示:


一定要调用一个类hiddenlabel并设置,visibility:hidden所以没有人真正看到标签.您可以在隐藏标签中以这种方式存储大量内容.

现在,在你的javascript中,要检索存储在标签中的信息(在这种情况下是客户端的ip地址),你可以这样做:

var ip = document.getElementById("ip").innerHTML;

现在你的变量"ip"等于ip地址.现在您可以将ip传递给您的API请求.

*编辑2年后* 两个小改进:

我经常使用这种方法,但是调用标签class="data",因为事实上,它是一种存储数据的方法.类名"hiddenlabel"是一种愚蠢的名字.

第二个修改是在样式表中,而不是visibility:hidden:

.data{
    display:none;
}

......是更好的方式.


不要将数据存储在DOM中.为什么有人会建议,即使是2年后呢?如果您可以将任何内容注入HTML文件,只需将该值注入JS变量即可.
周扒pi
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有