Skip to main content

Get Client IP Using jQuery

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

A few code snippets to Get Client IP Using JavaScript/jQuery.

1. One way

This one gives you longitude/latitude and timezone.

Try it!

$(document).ready( function() { $.getJSON( "https://smart-ip.net/geoip-json?callback=?", function(data){ alert( data.host); } );});

Returns:

?(
{
   source: "smart-ip.net",
   host: "14.200.158.65",
   lang: "en",
   countryName: "Australia",
   countryCode: "AU",
   city: "South Sydney Municipality",
   region: "New South Wales",
   latitude: "-33.9000",
   longitude: "151.2000",
   timezone: "Australia/NSW"
}
)

2. Two way

This one provides JSON.

Try it!

function myIP() {
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 
    xmlhttp.open("GET"," http://api.hostip.info/get_html.php ",false);
    xmlhttp.send();
 
    hostipInfo = xmlhttp.responseText.split("n");
 
    for (i=0; hostipInfo.length >= i; i++) {
        ipAddress = hostipInfo[i].split(":");
        if ( ipAddress[0] == "IP" ) return ipAddress[1];
    }
 
    return false;
}
 
// console.log(myIP());

Returns:

{
  country_name: "UNITED STATES",
  country_code: "US",
  city: "(Unknown city)",
  ip: "14.200.158.65"
}

3. Three way

Try it!

https://l2.io/ip.js
Syntax : https://l2.io/ip
Diplay Client IP address
--> x.x.x.x

Syntax : 
Display Client IP address in your HTML page using javascript
--> document.write('x.x.x.x');

Syntax : 
Set javascript variable "myip" to client IP address
--> myip = "x.x.x.x";

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn how Git works, and how to use it to streamline your workflow!


Google, Netflix and ILM are Python users. Maybe you should too?