通过第三方Web服务获取客户端IP地址 [英] Get client IP address via third party web service

查看:796
本文介绍了通过第三方Web服务获取客户端IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从以下页面阅读我的IP地址( http://l2.io/ip或其他)使用javascript将他保存在我的变量myIp中。

I would like to read my ip address from the following page(http://l2.io/ip or other) using javascript to save him in my variable "myIp".

function getMyIP() {
  var myIp;
  ...
  return myIp;
}

你怎么办?

推荐答案

检查链接网站,您可以包含脚本标记传递?var = desiredVarName 参数,该参数将被设置为包含IP地址的全局变量:

Checking your linked site, you may include a script tag passing a ?var=desiredVarName parameter which will be set as a global variable containing the IP address:

<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
                                                      <!-- ^^^^ -->
<script>alert(myip);</script>

演示

我相信我不必说这很容易被欺骗(通过使用代理服务器)或欺骗性请求标题),但无论如何都值得注意。

I believe I don't have to say that this can be easily spoofed (through either use of proxies or spoofed request headers), but it is worth noting in any case.

如果您的页面使用 https 协议提供服务,大多数浏览器将阻止使用提供的同一页面中的内容http 协议(包括脚本和图像),因此选项相当有限。如果你有<每天5k次点击,可以使用智能IP API 。例如:

In case your page is served using the https protocol, most browsers will block content in the same page served using the http protocol (that includes scripts and images), so the options are rather limited. If you have < 5k hits/day, the Smart IP API can be used. For instance:

<script>
var myip;
function ip_callback(o) {
    myip = o.host;
}
</script>
<script src="https://smart-ip.net/geoip-json?callback=ip_callback"></script>
<script>alert(myip);</script>

演示

编辑:显然,此 https 服务的证书已过期,因此用户必须手动添加例外。直接打开其API以检查证书状态: https://smart-ip.net/geoip-json

Apparently, this https service's certificate has expired so the user would have to add an exception manually. Open its API directly to check the certificate state: https://smart-ip.net/geoip-json

最有弹性和简单的方法,如果你有后端服务器逻辑,只需在< script> 标签内输出请求者的IP,这样你就不会需要依靠外部资源。例如:

The most resilient and simple way, in case you have back-end server logic, would be to simply output the requester's IP inside a <script> tag, this way you don't need to rely on external resources. For example:

PHP:

<script>var myip = '<?php echo $_SERVER['REMOTE_ADDR']; ?>';</script>

此处还有一个更加坚固的PHP解决方案(占有时由代理设置的标头) a href =https://stackoverflow.com/a/1641894/1331430>相关答案。

There's also a more sturdy PHP solution (accounting for headers that are sometimes set by proxies) in this related answer.

C#:

<script>var myip = '<%= Request.UserHostAddress %>';</script>

这篇关于通过第三方Web服务获取客户端IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆