Fly*_*wat 560 javascript jquery ip-address
我需要以某种方式使用JavaScript检索客户端的IP地址; 没有服务器端代码,甚至没有SSI.
但是,我并不反对使用免费的第三方脚本/服务.
thd*_*oan 660
我会使用一个可以返回JSON的Web服务(与jQuery一起使事情变得更简单).以下是我能找到的所有免费主动 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"
}
Run Code Online (Sandbox Code Playgroud)
限制:
试试看: http ://gd.geobytes.com/GetCityDetails
$.getJSON('http://gd.geobytes.com/GetCityDetails?callback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
返回:
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
限制:
试试吧: https ://json.geoiplookup.io/api
$.getJSON('https://json.geoiplookup.io/api?callback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
返回:
{
"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
}
Run Code Online (Sandbox Code Playgroud)
限制:
试试看: http ://www.geoplugin.net/json.gp
$.getJSON('http://www.geoplugin.net/json.gp?jsoncallback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
返回:
{
"geoplugin_request": "116.12.250.1",
"geoplugin_status": 200,
"geoplugin_credit": "Some of the returned data includes GeoLite data created by MaxMind, available from <a href=\\'http://www.maxmind.com\\'>http://www.maxmind.com</a>.",
"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
}
Run Code Online (Sandbox Code Playgroud)
限制:
试试看: 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
Run Code Online (Sandbox Code Playgroud)
限制:
试试吧: https ://ipapi.co/json/
$.getJSON('https://ipapi.co/json/', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
返回:
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
限制:
试试看: http ://ip-api.com/json
$.getJSON('http://ip-api.com/json?callback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
返回:
{
"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": ""
}
Run Code Online (Sandbox Code Playgroud)
限制:
试试吧: https ://api.ipdata.co
$.getJSON('https://api.ipdata.co', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
返回:
{
"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
}
}
Run Code Online (Sandbox Code Playgroud)
限制:
试试看: https ://ipfind.co/me?auuth = < 你的api密钥 >
$.getJSON('https://ipfind.co/me?auth=<your_api_key>', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
返回:
{
"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"
]
}
Run Code Online (Sandbox Code Playgroud)
限制:
Try it: https://api.ipgeolocation.io/ipgeo?apiKey=<your api key>
$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=<your_api_key>', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
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"
}
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
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));
});
Run Code Online (Sandbox Code Playgroud)
Returns:
{
"ip": "116.12.250.1"
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
Try it: https://api.ipinfodb.com/v3/ip-city/?key=<your api key>&format=json
$.getJSON('https://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&format=json&callback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
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"
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
Try it: https://ipinfo.io/json
$.getJSON('https://ipinfo.io/json', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
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"
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
Try it: http://api.ipstack.com/<ip address>?access_key=<your api key>
$.getJSON('https://api.ipregistry.co/?key=<your_api_key>', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
Try it: https://jsonip.com
$.getJSON('http://api.ipstack.com/<ip_address>?access_key=<your_api_key>', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
Try it: http://ip.jsontest.com/
$.getJSON('https://jsonip.com/?callback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
Returns:
{
"ip": "116.12.250.1",
"about": "/about",
"Pro!": "http://getjsonip.com",
"reject-fascism": "Liberal America will prevail"
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
Try it: https://geoip.nekudo.com/api
$.getJSON('http://ip.jsontest.com/?callback=?', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Run Code Online (Sandbox Code Playgroud)
Returns:
{
"ip": "116.12.250.1"
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
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));
});
Run Code Online (Sandbox Code Playgroud)
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"
}
Run Code Online (Sandbox Code Playgroud)
Limitations:
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
mid*_*ido 273
更新:我一直想创建一个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))Run Code Online (Sandbox Code Playgroud)
注意:如果您想要用户的所有IP(可能更多地取决于他的网络),这个新的缩小代码将仅返回单个IP,使用原始代码...
感谢WebRTC,在WebRTC支持的浏览器中获取本地IP非常容易(至少目前如此).我修改了源代码,减少了行数,没有发出任何眩晕请求,因为你只需要本地IP,而不是公共IP,下面的代码适用于最新的Firefox和Chrome,只需运行代码片段并自行检查:
function findIP(onNewIP) { // onNewIp - your listener function for new IPs
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)) return;
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
};
}
var ul = document.createElement('ul');
ul.textContent = 'Your IPs are: '
document.body.appendChild(ul);
function addIP(ip) {
console.log('got ip: ', ip);
var li = document.createElement('li');
li.textContent = ip;
ul.appendChild(li);
}
findIP(addIP);Run Code Online (Sandbox Code Playgroud)
<h1> Demo retrieving Client IP using WebRTC </h1>Run Code Online (Sandbox Code Playgroud)
这里发生的是,我们正在创建一个虚拟对等连接,并且为了让远程对等方联系我们,我们通常会互相交换冰候选者.并且读取冰候选者(来自本地会话描述和onIceCandidateEvent)我们可以告诉用户的IP.
我从哪里获取代码 - > 来源
Cha*_*ant 174
您可以通过服务器端使用JSONP进行转发
在谷歌搜索找到一个,在这里找到它可以使用客户端Javascript执行DNS查找(IP地址的主机名)?
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>
Run Code Online (Sandbox Code Playgroud)
注意:截至2015年11月15日, telize.com API已永久关闭.
Sho*_*og9 104
这里的大多数答案"解决"服务器端代码的需求...击中别人的服务器.这是一种完全有效的技术,除非您确实需要获取IP地址而不需要服务器.
传统上,如果没有某种插件,这是不可能的(即使这样,如果你在NAT路由器后面,你可能会得到错误的 IP地址),但随着WebRTC的出现,它实际上可以做到这一点. .如果你的目标是支持的WebRTC的浏览器(目前为:火狐,Chrome和Opera).
有关如何使用WebRTC检索有用的客户端IP地址的详细信息,请阅读mido的答案.
inu*_*huk 81
你可以对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;
}
Run Code Online (Sandbox Code Playgroud)
作为奖励,地理定位信息在同一个呼叫中返回.
Sri*_*r R 75
试试这个
$.get("http://ipinfo.io", function(response) {
alert(response.ip);
}, "jsonp");
Run Code Online (Sandbox Code Playgroud)
要么
$(document).ready(function () {
$.getJSON("http://jsonip.com/?callback=?", function (data) {
console.log(data);
alert(data.ip);
});
});
Run Code Online (Sandbox Code Playgroud)
Ste*_*fer 62
你不能.你必须问一个服务器.
Flo*_*ock 60
根据他们:
- 您可以无限制地使用它(即使您每分钟执行数百万次请求).
- ipify是完全开源的(查看GitHub存储库).
这是一个有效的JS示例(而不是想知道为什么这个答案的票数很少,请亲自尝试看看它的实际效果):
<script>
function getIP(json) {
alert("My public IP address is: " + json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
Run Code Online (Sandbox Code Playgroud)
太懒了复制/粘贴?我喜欢.这是一个演示
太懒了点击? :O
注意:在运行演示之前关闭Adblock Plus/uBlock&co ..否则,它将无效.
我与IPify团队无关.我认为有人会为一般商品提供这样的服务真是太酷了.
Ben*_*ing 26
您可以使用我的服务http://ipinfo.io,它将为您提供客户端IP,主机名,地理位置信息和网络所有者.这是一个记录IP的简单示例:
$.get("http://ipinfo.io", function(response) {
console.log(response.ip);
}, "jsonp");
Run Code Online (Sandbox Code Playgroud)
这是一个更详细的JSFiddle示例,它还打印出完整的响应信息,因此您可以看到所有可用的详细信息:http://jsfiddle.net/zK5FN/2/
use*_*951 16
我想说乍得和马耳他有很好的答案.然而,他们很复杂.所以我建议我通过国家/地区插件从广告中找到此代码
<script>
<script language="javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="javascript">
mmjsCountryCode = geoip_country_code();
mmjsCountryName = geoip_country_name();
</script>
Run Code Online (Sandbox Code Playgroud)
没有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 ''; }
Run Code Online (Sandbox Code Playgroud)
它还没有真正回答这个问题,因为
http://j.maxmind.com/app/geoip.js不包含IP(虽然我打赌它使用IP来获取国家).
但是制作一个像PhP这样的PhP脚本是如此容易
function visitorsIP() { return '123.123.123.123'; }
Run Code Online (Sandbox Code Playgroud)
做那个.穿上http://yourdomain.com/yourip.php.
然后做
<script language="javascript" src="http://yourdomain.com/yourip.php"></script>
Run Code Online (Sandbox Code Playgroud)
问题特别提到不要使用第三方脚本.没有其他办法.Javascript无法知道您的IP.但是其他可以通过javascript访问的服务器可以正常工作而没有问题.
BRe*_*bey 15
这个问题有两种解释.大多数人将"客户端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)
}
);
Run Code Online (Sandbox Code Playgroud)
<h1>Demo "Waitable" Client IP Retrieval using WebRTC </h1>Run Code Online (Sandbox Code Playgroud)
Cyr*_*pta 13
好吧,我对这个问题很离题,但今天我有类似的需求,虽然我无法使用Javascript从客户端找到ID,但我做了以下操作.
在服务器端: -
<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>
Run Code Online (Sandbox Code Playgroud)
使用Javascript
var ip = $get("uip").innerHTML;
Run Code Online (Sandbox Code Playgroud)
我正在使用ASP.Net Ajax,但您可以使用getElementById而不是$ get().
发生了什么,我在页面上有一个隐藏的div元素,用户的IP从服务器呈现.比Javascript我只是加载该值.
对于像你这样有类似要求的人来说这可能会有所帮助(就像我一样,但我没想到这一点).
干杯!
小智 13
使用Smart-IP.net Geo-IP API.例如,通过使用jQuery:
$(document).ready( function() {
$.getJSON( "http://smart-ip.net/geoip-json?callback=?",
function(data){
alert( data.host);
}
);
});
Run Code Online (Sandbox Code Playgroud)
小智 13
有一种更简单,更自由的方法,不会要求访问者获得任何许可.
它包括向http://freegeoip.net/json提交一个非常简单的Ajax POST请求.收到位置信息后,在JSON中,您会通过更新页面或重定向到新页面来做出相应的反应.
以下是您提交位置信息请求的方式:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
console.log(location)
}
} );
Run Code Online (Sandbox Code Playgroud)
用jQuery获取你的IP
您可以使用一行JS获取您的公共IP地址吗?有免费服务为您提供此服务,您只需要获取请求即可:
$.get('http://jsonip.com/', function(r){ console.log(r.ip); });
Run Code Online (Sandbox Code Playgroud)
要使上述代码段起作用,您的浏览器必须支持CORS(跨源请求共享).否则会抛出安全异常.在旧版浏览器中,您可以使用此版本,该版本使用JSON-P请求:
$.getJSON('http://jsonip.com/?callback=?', function(r){ console.log(r.ip); });
Run Code Online (Sandbox Code Playgroud)
您可以使用userinfo.io javascript库.
<script type="text/javascript" src="userinfo.0.0.1.min.js"></script>
UserInfo.getInfo(function(data) {
alert(data.ip_address);
}, function(err) {
// Do something with the error
});
Run Code Online (Sandbox Code Playgroud)
您还可以使用requirejs加载脚本.
它将为您提供访问者的IP地址,以及其位置(国家,城市等)的一些数据.它基于maxmind geoip数据库.
免责声明:我写了这个库
Javascript/jQuery获取客户的IP地址和位置(国家,城市)
您只需要将带有"src"链接的标记嵌入到服务器中.服务器将返回"codehelper_ip"作为Object/JSON,您可以立即使用它.
// First, embed this script in your head or at bottom of the page.
<script language="Javascript" src="http://www.codehelper.io/api/ips/?js"></script>
// You can use it
<script language="Javascript">
alert(codehelper_ip.IP);
alert(codehelper_ip.Country);
</script>
Run Code Online (Sandbox Code Playgroud)
有关Javascript的详细信息,请检测Real IP Address Plus国家/地区
如果您使用的是jquery,可以尝试:
console.log(codehelper_ip);
Run Code Online (Sandbox Code Playgroud)
它将显示有关返回对象的更多信息.
如果你想要回调函数,请试试这个:
// First, embed this script in your head or at bottom of the page.
<script language="Javascript" src="http://www.codehelper.io/api/ips/?callback=yourcallback"></script>
// You can use it
<script language="Javascript">
function yourcallback(json) {
alert(json.IP);
}
</script>
Run Code Online (Sandbox Code Playgroud)
小智 8
Appspot.com回调的服务不可用.ipinfo.io似乎正在运作.
我做了一个额外的步骤,并使用AngularJS检索所有地理信息.(感谢里卡多)看看吧.
<div ng-controller="geoCtrl">
<p ng-bind="ip"></p>
<p ng-bind="hostname"></p>
<p ng-bind="loc"></p>
<p ng-bind="org"></p>
<p ng-bind="city"></p>
<p ng-bind="region"></p>
<p ng-bind="country"></p>
<p ng-bind="phone"></p>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular-route.min.js"></script>
<script>
'use strict';
var geo = angular.module('geo', [])
.controller('geoCtrl', ['$scope', '$http', function($scope, $http) {
$http.jsonp('http://ipinfo.io/?callback=JSON_CALLBACK')
.success(function(data) {
$scope.ip = data.ip;
$scope.hostname = data.hostname;
$scope.loc = data.loc; //Latitude and Longitude
$scope.org = data.org; //organization
$scope.city = data.city;
$scope.region = data.region; //state
$scope.country = data.country;
$scope.phone = data.phone; //city area code
});
}]);
</script>
Run Code Online (Sandbox Code Playgroud)
工作页面:http://www.orangecountyseomarketing.com/projects/_ip_angularjs.html
获取客户端计算机的IP地址并不是一种可靠的方法.
这经历了一些可能性.如果用户具有多个接口,则使用Java的代码将中断.
http://nanoagent.blogspot.com/2006/09/how-to-find-evaluate-remoteaddrclients.html
从这里查看其他答案,听起来您可能想要获取客户端的公共IP地址,这可能是他们用来连接到互联网的路由器的地址.这里有很多其他答案都在谈论这个问题.我建议创建和托管您自己的服务器端页面,以接收请求并使用IP地址进行响应,而不是依赖于可能会或可能不会继续工作的其他人的服务.
如果你要包含一个文件,你可以做一个简单的ajax get:
function ip_callback() {
$.get("ajax.getIp.php",function(data){ return data; }
}
Run Code Online (Sandbox Code Playgroud)
而ajax.getIp.php会是这样:
<?=$_SERVER['REMOTE_ADDR']?>
Run Code Online (Sandbox Code Playgroud)
我非常喜欢,api.ipify.org因为它支持HTTP和HTTPS.
以下是api.ipify.org使用jQuery 获取IP的一些示例.
https://api.ipify.org?format=json
Run Code Online (Sandbox Code Playgroud)
$.getJSON("https://api.ipify.org/?format=json", function(e) {
alert(e.ip);
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
http://api.ipify.org?format=json
Run Code Online (Sandbox Code Playgroud)
$.getJSON("http://api.ipify.org/?format=json", function(e) {
alert(e.ip);
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
如果您不希望它在JSON中,则还会通过HTTPS进行明文响应
https://api.ipify.org
Run Code Online (Sandbox Code Playgroud)
而且还有一个基于HTTP的明文响应
http://api.ipify.org
Run Code Online (Sandbox Code Playgroud)
如果您在某处使用 NGINX,您可以添加此代码片段并通过任何 AJAX 工具询问您自己的服务器。
location /get_ip {
default_type text/plain;
return 200 $remote_addr;
}
Run Code Online (Sandbox Code Playgroud)
使用ipdata.co.
API还提供地理定位数据,并拥有10个全局端点,每个端点每天可处理超过80000个请求!
这个答案使用的"测试"API密钥非常有限,仅用于测试几个调用.注册您自己的免费API密钥,每天最多可获得1500个请求以进行开发.
$.get("https://api.ipdata.co?api-key=test", function (response) {
$("#response").html(response.ip);
}, "jsonp");Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="response"></pre>Run Code Online (Sandbox Code Playgroud)
我想提供一种方法,当我想在html页面中存储信息时,我会使用很多方法,并希望我的javascript读取信息而不必将参数传递给javascript.当您的脚本在外部引用而不是内联时,这尤其有用.
但是,它不符合"无服务器端脚本"的标准.但是,如果您可以在html中包含服务器端脚本,请执行以下操作:
在html页面的底部,在最终正文标记的正上方创建隐藏的标签元素.
您的标签将如下所示:
<label id="ip" class="hiddenlabel"><?php echo $_SERVER['REMOTE_ADDR']; ?></label>
Run Code Online (Sandbox Code Playgroud)
一定要调用一个类hiddenlabel并设置,visibility:hidden所以没有人真正看到标签.您可以在隐藏标签中以这种方式存储大量内容.
现在,在你的javascript中,要检索存储在标签中的信息(在这种情况下是客户端的ip地址),你可以这样做:
var ip = document.getElementById("ip").innerHTML;
Run Code Online (Sandbox Code Playgroud)
现在你的变量"ip"等于ip地址.现在您可以将ip传递给您的API请求.
*编辑2年后* 两个小改进:
我经常使用这种方法,但是调用标签class="data",因为事实上,它是一种存储数据的方法.类名"hiddenlabel"是一种愚蠢的名字.
第二个修改是在样式表中,而不是visibility:hidden:
.data{
display:none;
}
Run Code Online (Sandbox Code Playgroud)
......是更好的方式.
获取系统本地IP:
try {
var RTCPeerConnection = window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({ iceServers: [] });
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', { reliable: false });
};
rtc.onicecandidate = function (evt) {
if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
LgIpDynAdd = displayAddrs.join(" or perhaps ") || "n/a";
alert(LgIpDynAdd)
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
alert(addr);
}
});
}
})();} catch (ex) { }
Run Code Online (Sandbox Code Playgroud)
$.getJSON("http://jsonip.com?callback=?", function (data) {
alert("Your ip address: " + data.ip);
});
Run Code Online (Sandbox Code Playgroud)
试试这个:http : //httpbin.org/ip(或https://httpbin.org/ip)
https的示例:
$.getJSON('https://httpbin.org/ip', function(data) {
console.log(data['origin']);
});
Run Code Online (Sandbox Code Playgroud)
资料来源:http : //httpbin.org/
首先是实际答案:不可能仅使用客户端执行的代码来找到您自己的IP地址。
但是,您只需对https://api.muctool.de/whois进行GET 并收到类似获取客户端IP地址的信息
{
"ip": "88.217.152.15",
"city": "Munich",
"isp": "M-net Telekommunikations GmbH",
"country": "Germany",
"countryIso": "DE",
"postalCode": "80469",
"subdivisionIso": "BY",
"timeZone": "Europe/Berlin",
"cityGeonameId": 2867714,
"countryGeonameId": 2921044,
"subdivisionGeonameId": 2951839,
"ispId": 8767,
"latitude": 48.1299,
"longitude": 11.5732,
"fingerprint": "61c5880ee234d66bded68be14c0f44236f024cc12efb6db56e4031795f5dc4c4",
"session": "69c2c032a88fcd5e9d02d0dd6a5080e27d5aafc374a06e51a86fec101508dfd3",
"fraud": 0.024,
"tor": false
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1036439 次 |
| 最近记录: |