简体   繁体   中英

Find IP address using jQuery

I tried to get my IP using the following code:

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

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. The code will change depending on the language of your web application.

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.

Several snippets for server-side code options

In JSP

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

In PHP

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

In ASP

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

In ASP.NET

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

In Cold Fusion

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

Reference: Obtaining Your Visitor's IP Address

<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

you can get your public IP address with one line of JS? 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). Otherwise a security exception would be thrown. In older browsers, you can use this version, which uses a JSON-P request:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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