简体   繁体   English

使用javascript获取IP地址

[英]Get ip address using javascript

I just want to ask, is there a way on how to get ip addresses using javascript only? 我只是想问,有没有办法如何只使用javascript获取IP地址? been searching for quite a while now and most of the results were I need to use api(s). 现在已经搜索了很长一段时间,大部分结果都是我需要使用api(s)。 I have used this webrtc and it works great but it's not working on IE, API is great, I've tested some and that works great in different browsers. 我已经使用过这个webrtc而且效果很好,但它不适用于IE,API很棒,我测试了一些,并且在不同的浏览器中运行良好。

but I need to get the code itself from api, or is it possible to get/extract the code from api itself and make a specified file for the source so I won't rely on source from the internet? 但我需要从api获取代码本身,或者是否可以从api本身获取/提取代码并为源代码生成指定文件,这样我就不会依赖来自Internet的源代码了?

I need the RAW file from api, because if ever the src of the api went down, my site will be affected too, so I want it to get and create a external source and include it on my site. 我需要来自api的RAW文件,因为如果api的src发生故障,我的网站也会受到影响,所以我希望它能够获取并创建一个外部源并将其包含在我的网站上。

Try following solution :- 尝试以下解决方案: -

First option :- 第一种选择: -

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

Second option :- 第二种选择: -

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

It may help you. 它可能会帮助你。

I could be wrong, but I think you can only detect the IP serverside, so you'll have to do some kind of a get/post request. 我可能是错的,但我认为你只能检测IP服务器端,所以你必须做某种get / post请求。

The other answer shows a possible implementation of this. 另一个答案显示了可能的实现。

Also, see this question: How to get client's IP address using javascript only? 此外,请参阅此问题: 如何仅使用javascript获取客户端的IP地址?

You need to create script at backend of your site, that will be return IP, and execute it via ajax. 您需要在站点的后端创建脚本,该脚本将返回IP,并通过ajax执行。

Or on the stage of generating page (at backend), you can detect IP, and put it to cookie, than read cookie from JS: 或者在生成页面的阶段(在后端),您可以检测IP,并将其放入cookie,而不是从JS读取cookie:

function getCookie(name) {
  var matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

If you want source data you can get it from MaxMind: http://dev.maxmind.com/geoip/ There is a free and a paid version. 如果您需要源数据,可以从MaxMind获取: http ://dev.maxmind.com/geoip/有免费和付费版本。 Most of the IP info providers uses that library. 大多数IP信息提供者都使用该库。

If you only need the IP, you can create a script of your own. 如果您只需要IP,则可以创建自己的脚本。 Just create a backend script something like with PHP and request it from JS. 只需像PHP一样创建一个后端脚本,并从JS请求它。 Example: http://php.about.com/od/learnphp/qt/record_user_ip.htm 示例: http//php.about.com/od/learnphp/qt/record_user_ip.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM