2

I want to get the user's IP address with jQuery or JavaScript, it doesn't really matter but I prefer jQuery.

I've seen some answers here but they didn't work for me.

1

4 Answers 4

5

This has been taken from How to get client IP address using jQuery

$.getJSON("http://jsonip.appspot.com?callback=?",
    function(data){
       alert( "Your ip: " + data.ip);
  });
Sign up to request clarification or add additional context in comments.

2 Comments

I swear i saw that snippet but it didn't work 15 min ago, might have been my internet connection sorry.
@andrei: Don’t worry it happens some times.
3

That isn't exposed to javascript, but if you really need it you could spit it out in your markup (assuming php):

<head>
<meta name="ip" content="<?php echo $_SERVER["REMOTE_ADDR"] ?>">
–
<script>$(function(){ alert( $("meta[name=ip]").attr("content") ) })</script>

Not sure why you would want to though, javascript runs on the client, so when would you need its ip? From javascript's perspective, it is safe to assume that the user's ip is 127.0.0.1.

Comments

2

You cannot do it with just client side code.. you would need to user a server side page and use jquery to load the value into a div using jsonP or something

Comments

0

My personal favorite (comes with some bonus'!):


$.ajax({
    dataType: 'json',
    url: 'http://api.hostip.info/get_json.php',
    success: function(data) {
        var $ip = data['ip'],
            $city = data['city'],
            $countryCode = data['country_code'],
            $countryName = data['country_name'];
    }
});

Example Example Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.