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

然而,我并不反对使用免费的第三方脚本/服务。


当前回答

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

你只需要嵌入一个带有“src”链接的标签到服务器。服务器将以Object / JSON的形式返回“codehelper_ip”,您可以立即使用它。

// 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>

更多信息在Javascript检测真实IP地址加国家

如果你正在使用jQUery,你可以尝试:

console.log(codehelper_ip); 

它将显示关于返回对象的更多信息。

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

// 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>

其他回答

首先是实际的答案:不可能仅使用客户端执行的代码来找出您自己的IP地址。

但是,您可以对https://hutils.loxal.net/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
}

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

下面是一些使用jQuery获取IP的例子。

基于HTTPS的JSON格式

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

$.getJSON(“https://api.ipify.org/?format=json”, function(e) { 警报(e.ip); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script>

基于HTTP的JSON格式

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

$.getJSON(“http://api.ipify.org/?format=json”, function(e) { 警报(e.ip); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script>

基于HTTPS的文本格式

如果你不想要JSON格式,也有一个通过HTTPS的明文响应

https://api.ipify.org

基于HTTP的文本格式

在HTTP上也有明文响应

http://api.ipify.org

您可以通过服务器端与JSONP进行中继

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

<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>

注意:telize.com API已于2015年11月15日永久关闭。

如果你在某个地方使用NGINX,你可以添加这个片段并通过任何AJAX工具询问你自己的服务器。

location /get_ip {
    default_type text/plain;
    return 200 $remote_addr;
}

实际上没有可靠的方法来获取客户端计算机的IP地址。

这涉及到一些可能性。如果用户有多个接口,那么使用Java的代码将会中断。

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

从这里的其他答案来看,听起来您可能想要获得客户端的公共IP地址,这可能是他们用来连接到互联网的路由器的地址。很多其他的答案都谈到了这个。我建议创建并托管您自己的服务器端页面,用于接收请求并使用IP地址响应,而不是依赖于其他人的服务,因为其他人的服务可能继续工作,也可能无法继续工作。