简体   繁体   English

使用jQuery查找IP地址

[英]Find IP address using jQuery

I tried to get my IP using the following code: 我试图使用以下代码获取我的IP:

$.getJSON("http://jsonip.appspot.com?callback=?", function(data){ip=data.ip});

But it doesn't seems to work for me. 但它似乎对我不起作用。 Please Help. 请帮忙。

Thanks in advance. 提前致谢。

You can use this site to acquire your IP with JSON. 您可以使用此站点通过JSON获取IP。

http://jsonip.com http://jsonip.com

You need to send a ajax request to your backend web server and respond to ajax request with the requesting client's ip back from the server. 您需要向后端Web服务器发送ajax请求,并使用请求客户端的ip从服务器返回响应ajax请求。 The code will change depending on the language of your web application. 代码将根据Web应用程序的语言而变化。

JavaScript itself has no way of reading the IP address of the local computer and so for JavaScript to obtain that information we need to use a different language to obtain the information. JavaScript本身无法读取本地计算机的IP地址,因此JavaScript要获取该信息,我们需要使用不同的语言来获取信息。

Several snippets for server-side code options 服务器端代码选项的几个片段

In JSP 在JSP中

ip = '<%=request.getRemoteAddr()%>';

In PHP 在PHP中

ip = "<?php echo $_SERVER['REMOTE_ADDR']?>";

In ASP 在ASP中

ip = '<%= Request.ServerVariables("REMOTE_ADDR")%>';

In ASP.NET 在ASP.NET中

ip = '<%= Request.UserHostAddress>';

In Cold Fusion 在Cold Fusion中

ip = '<cfoutput>#cgi.remote_addr#</cfoutput>';

Reference: Obtaining Your Visitor's IP Address 参考: 获取访客的IP地址

<script type="application/javascript">
function getip(json){
  alert(json.ip); // alerts the ip address
}

<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>

Get your IP with jQuery 用jQuery获取你的IP

you can get your public IP address with one line of JS? 您可以通过一行JS获取您的公共IP地址吗? There is a free service that offers this for you and a get request is all that you need to do: 有免费服务为您提供此服务,您只需要获取请求即可:

   $.get('http://jsonip.com/', function(r){ console.log(r.ip); });

For the above snippet to work, your browser will have to support CORS (cross-origin request sharing). 要使上述代码段起作用,您的浏览器必须支持CORS(跨源请求共享)。 Otherwise a security exception would be thrown. 否则会抛出安全异常。 In older browsers, you can use this version, which uses a JSON-P request: 在旧版浏览器中,您可以使用此版本,该版本使用JSON-P请求:

   $.getJSON('http://jsonip.com/?callback=?', function(r){ console.log(r.ip); });

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

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