Breaking

Thursday, October 17, 2019

[Solved] How to get client's IP address using JavaScript?

how to get client's IP address using Javascript

How to get the client's IP address using JavaScript?

What is an IP address?

The IP address is a passport to the Internet.
Here's a "pocket definition" that you can use if someone asked. "It's a network address for your computer so the Internet knows where to send you emails, data, etc."

The IP address is a fascinating product of modern computer technology designed to allow one connected computer (or "smart" device) to communicate with another device over the Internet.

IP addresses allow the location of literally billions of digital devices that are connected to the Internet to be pinpointed and differentiated from other devices.

Here's the example

Your house has a street address to get mail; your connected device has an Internet address to get and receive data on the Web.
Your home as a street number; your laptop, smartphone or your lights, baby monitor, thermostat (anything device that connects to the Internet and works wirelessly) has an Internet number. (That's what the Internet of Things is all about.)

The common type of IP address (is known as IPv4, for "version 4"). Here's an example of what an IP address might look like:
66.171.248.170

An IPv4 address consists of four numbers, each of which contains one to three digits, with a single dot (.) separating each number or set of digits. Each of the four numbers can range from 0 to 255.

It's called IPv6 and it offers a maximum number of IP address for today and for the future.

Whereas IPv4 supports a maximum of approximately 4.3 billion unique IP addresses, IPv6 supports, in theory, a maximum number that will never run out.

An IPv6 address consists of eight groups of four hexadecimal digits. If a group consists of four zeros, the notation can be shortened using a colon to replace the zeros. Here's an example IPv6 address:

2001:0db8:85a3:0000:0000:8a2e:0370:7334

How to get the client's IP address using JavaScript?

the following code will return the IP address of customer using core JS


(1)
var findIP = new Promise(r=>{var w=window,a=new (w.RTCPeerConnection||w.mozRTCPeerConnection||w.webkitRTCPeerConnection)({iceServers:[]}),b=()=>{};a.createDataChannel("");a.createOffer(c=>a.setLocalDescription(c,b,b),b);a.onicecandidate=c=>{try{c.candidate.candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g).forEach(r)}catch(e){}}})

/*Usage example*/
findIP.then(ip => document.write('your ip: ', ip)).catch(e => console.error(e))


(2)
function findIP(onNewIP) { //  onNewIp - your listener function for new IPs
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
  var pc = new myPeerConnection({iceServers: []}),
    noop = function() {},
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

  function ipIterate(ip) {
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  }
  pc.createDataChannel(""); //create a bogus data channel
  pc.createOffer(function(sdp) {
    sdp.sdp.split('\n').forEach(function(line) {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(ipIterate);
    });
    pc.setLocalDescription(sdp, noop, noop);
  }, noop); // create offer and set local description
  pc.onicecandidate = function(ice) { //listen for candidate events
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
  };
}



var ul = document.createElement('ul');
ul.textContent = 'Your IPs are: '
document.body.appendChild(ul);

function addIP(ip) {
  console.log('got ip: ', ip);
  var li = document.createElement('li');
  li.textContent = ip;
  ul.appendChild(li);
}

findIP(addIP);


the following code will return the IP address of customer using core APIs


I would use a web service that can return JSON (along with jQuery to make things simpler). Below are all the free active IP lookup services I could find and the information they return.

(1) DB-IP
Try it: http://api.db-ip.com/addrinfo?api_key=<your api key>&addr=<ip address>

Returns:

{
  "address": "116.12.250.1",
  "country": "SG",
  "stateprov": "Central Singapore",
  "city": "Singapore"
}
Limitations:

2,500 requests per day
Doesn't support JSONP callbacks
Requires IP address parameter
Requires an email address to get your API key
No SSL (https) with the free plan

(2) ipapi.co
Try it: https://ipapi.co/json/

$.getJSON('https://ipapi.co/json/', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "ip": "116.12.250.1",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "country": "SG",
  "country_name": "Singapore",
  "postal": null,
  "latitude": 1.2855,
  "longitude": 103.8565,
  "timezone": "Asia/Singapore"
}

Limitations:

1,000 requests per day
Requires SSL (https)

(3) Geobytes
Try it: http://gd.geobytes.com/GetCityDetails

$.getJSON('http://gd.geobytes.com/GetCityDetails?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "geobytesforwarderfor": "",
  "geobytesremoteip": "116.12.250.1",
  "geobytesipaddress": "116.12.250.1",
  "geobytescertainty": "99",
  "geobytesinternet": "SA",
  "geobytescountry": "Saudi Arabia",
  "geobytesregionlocationcode": "SASH",
  "geobytesregion": "Ash Sharqiyah",
  "geobytescode": "SH",
  "geobyteslocationcode": "SASHJUBA",
  "geobytescity": "Jubail",
  "geobytescityid": "13793",
  "geobytesfqcn": "Jubail, SH, Saudi Arabia",
  "geobyteslatitude": "27.004999",
  "geobyteslongitude": "49.660999",
  "geobytescapital": "Riyadh ",
  "geobytestimezone": "+03:00",
  "geobytesnationalitysingular": "Saudi Arabian ",
  "geobytespopulation": "22757092",
  "geobytesnationalityplural": "Saudis",
  "geobytesmapreference": "Middle East ",
  "geobytescurrency": "Saudi Riyal",
  "geobytescurrencycode": "SAR",
  "geobytestitle": "Saudi Arabia"
}

Limitations:

16,384 requests per hour
No SSL (https) with the free plan
Can return the wrong location (I'm in Singapore, not Saudi Arabia)


(4) GeoIPLookup.io
Try it: https://json.geoiplookup.io/api

$.getJSON('https://json.geoiplookup.io/api?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
    "ip": "116.12.250.1",
    "isp": "SGPOST",
    "org": "Singapore Post Ltd",
    "hostname": "116.12.250.1",
    "longitude": "103.807",
    "latitude": "1.29209",
    "postal_code": "",
    "city": "Singapore",
    "country_code": "SG",
    "country_name": "Singapore",
    "continent_code": "AS",
    "region": "Central Singapore",
    "district": "",
    "timezone_name": "Asia\/Singapore",
    "connection_type": "",
    "asn": "AS3758 SingNet",
    "currency_code": "SGD",
    "currency_name": "Singapore Dollar",
    "success": true
}
Limitations:

Unknown


(5) geoPlugin
Try it: http://www.geoplugin.net/json.gp

$.getJSON('http://www.geoplugin.net/json.gp?jsoncallback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});

Returns:

{
  "geoplugin_request": "116.12.250.1",
  "geoplugin_status": 200,
  "geoplugin_credit": "Some of the returned data includes GeoLite data created by MaxMind, available from <a href=\\'http://www.maxmind.com\\'>http://www.maxmind.com</a>.",
  "geoplugin_city": "Singapore",
  "geoplugin_region": "Singapore (general)",
  "geoplugin_areaCode": "0",
  "geoplugin_dmaCode": "0",
  "geoplugin_countryCode": "SG",
  "geoplugin_countryName": "Singapore",
  "geoplugin_continentCode": "AS",
  "geoplugin_latitude": "1.2931",
  "geoplugin_longitude": "103.855797",
  "geoplugin_regionCode": "00",
  "geoplugin_regionName": "Singapore (general)",
  "geoplugin_currencyCode": "SGD",
  "geoplugin_currencySymbol": "&#36;",
  "geoplugin_currencySymbol_UTF8": "$",
  "geoplugin_currencyConverter": 1.4239
}
Limitations:

120 requests per minute
No SSL (https) with the free plan


(6) Hacker Target
Try it: https://api.hackertarget.com/geoip/?q=<ip address>

Returns:

IP Address: 116.12.250.1
Country: SG
State: N/A
City: Singapore
Latitude: 1.293100
Longitude: 103.855797

Limitations:

50 requests per day
Doesn't support JSONP callbacks
Requires IP address parameter
Returns plain text




(7) IP-API.com
Try it: http://ip-api.com/json

$.getJSON('http://ip-api.com/json?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "as": "AS3758 SingNet",
  "city": "Singapore",
  "country": "Singapore",
  "countryCode": "SG",
  "isp": "SingNet Pte Ltd",
  "lat": 1.2931,
  "lon": 103.8558,
  "org": "Singapore Telecommunications",
  "query": "116.12.250.1",
  "region": "01",
  "regionName": "Central Singapore Community Development Council",
  "status": "success",
  "timezone": "Asia/Singapore",
  "zip": ""
}
Limitations:

150 requests per minute
No SSL (https) with the free plan

(8) Ipdata.co
Try it: https://api.ipdata.co

$.getJSON('https://api.ipdata.co', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip": "116.12.250.1",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "region_code": "01",
  "country_name": "Singapore",
  "country_code": "SG",
  "continent_name": "Asia",
  "continent_code": "AS",
  "latitude": 1.2931,
  "longitude": 103.8558,
  "asn": "AS3758",
  "organisation": "SingNet",
  "postal": "",
  "calling_code": "65",
  "flag": "https://ipdata.co/flags/sg.png",
  "emoji_flag": "\ud83c\uddf8\ud83c\uddec",
  "emoji_unicode": "U+1F1F8 U+1F1EC",
  "is_eu": false,
  "languages": [
    {
      "name": "English",
      "native": "English"
    },
    {
      "name": "Malay",
      "native": "Bahasa Melayu"
    },
    {
      "name": "Tamil",
      "native": "\u0ba4\u0bae\u0bbf\u0bb4\u0bcd"
    },
    {
      "name": "Chinese",
      "native": "\u4e2d\u6587"
    }
  ],
  "currency": {
    "name": "Singapore Dollar",
    "code": "SGD",
    "symbol": "S$",
    "native": "$",
    "plural": "Singapore dollars"
  },
  "time_zone": {
    "name": "Asia/Singapore",
    "abbr": "+08",
    "offset": "+0800",
    "is_dst": false,
    "current_time": "2018-05-09T12:28:49.183674+08:00"
  },
  "threat": {
    "is_tor": false,
    "is_proxy": false,
    "is_anonymous": false,
    "is_known_attacker": false,
    "is_known_abuser": false,
    "is_threat": false,
    "is_bogon": false
  }
}
Limitations:

1,500 requests per day
Requires an email address to get your API key
Requires SSL (https)


(9) IP Find
Try it: https://ipfind.co/me?auth=<your api key>

$.getJSON('https://ipfind.co/me?auth=<your_api_key>', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip_address": "116.12.250.1",
  "country": "Singapore",
  "country_code": "SG",
  "continent": "Asia",
  "continent_code": "AS",
  "city": "Singapore",
  "county": null,
  "region": "Central Singapore",
  "region_code": "01",
  "timezone": "Asia/Singapore",
  "owner": null,
  "longitude": 103.8565,
  "latitude": 1.2855,
  "currency": "SGD",
  "languages": [
    "cmn",
    "en-SG",
    "ms-SG",
    "ta-SG",
    "zh-SG"
  ]
}
Limitations:

300 requests per day
Requires registration to get your API key


(10) ipgeolocation
Try it: https://api.ipgeolocation.io/ipgeo?apiKey=<your api key>

$.getJSON('https://api.ipgeolocation.io/ipgeo?apiKey=<your_api_key>', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip": "116.12.250.1",
  "continent_code": "AS",
  "continent_name": "Asia",
  "country_code2": "SG",
  "country_code3": "SGP",
  "country_name": "Singapore",
  "country_capital": "Singapore",
  "state_prov": "Central Singapore",
  "district": "",
  "city": "Singapore",
  "zipcode": "",
  "latitude": "1.29209",
  "longitude": "103.807",
  "is_eu": false,
  "calling_code": "+65",
  "country_tld": ".sg",
  "languages": "cmn,en-SG,ms-SG,ta-SG,zh-SG",
  "country_flag": "https://ipgeolocation.io/static/flags/sg_64.png",
  "isp": "SGPOST",
  "connection_type": "",
  "organization": "Singapore Post Ltd",
  "geoname_id": "1880252",
  "currency": {
    "name": "Dollar",
    "code": "SGD"
  },
  "time_zone": {
    "name": "Asia/Singapore",
    "offset": 8,
    "is_dst": false,
    "current_time": "2018-06-12 09:06:49.028+0800"
  }
}
Limitations:

50,000 requests per month
Requires registration to get your API key


(11) ipify
Try it: https://api.ipify.org/?format=json

$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip": "116.12.250.1"
}
Limitations:

None


(12)IPInfoDB
Try it: https://api.ipinfodb.com/v3/ip-city/?key=<your api key>&format=json

$.getJSON('https://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&format=json&callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "statusCode": "OK",
  "statusMessage": "",
  "ipAddress": "116.12.250.1",
  "countryCode": "SG",
  "countryName": "Singapore",
  "regionName": "Singapore",
  "cityName": "Singapore",
  "zipCode": "048941",
  "latitude": "1.28967",
  "longitude": "103.85",
  "timeZone": "+08:00"
}
Limitations:

Two requests per second
Requires registration to get your API key


(13) ipinfo.io
Try it: https://ipinfo.io/json

$.getJSON('https://ipinfo.io/json', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip": "116.12.250.1",
  "hostname": "No Hostname",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "country": "SG",
  "loc": "1.2931,103.8558",
  "org": "AS3758 SingNet"
}
Limitations:

1,000 requests per day


(14)Ipregistry
Try it: https://api.ipregistry.co/?key=<your api key>

$.getJSON('https://api.ipregistry.co/?key=<your_api_key>', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip" : "116.12.250.1",
  "type" : "IPv4",
  "hostname" : null,
  "carrier" : {
    "name" : null,
    "mcc" : null,
    "mnc" : null
  },
  "connection" : {
    "asn" : 3758,
    "domain" : "singnet.com.sg",
    "organization" : "SingNet Pte Ltd",
    "type" : "isp"
  },
  "currency" : {
    "code" : "SGD",
    "name" : "Singapore Dollar",
    "plural" : "Singapore dollars",
    "symbol" : "SGD",
    "symbol_native" : "SGD",
    "format" : {
      "negative" : {
        "prefix" : "-SGD",
        "suffix" : ""
      },
      "positive" : {
        "prefix" : "SGD",
        "suffix" : ""
      }
    }
  },
  "location" : {
    "continent" : {
      "code" : "AS",
      "name" : "Asia"
    },
    "country" : {
      "area" : 692.0,
      "borders" : [ ],
      "calling_code" : "65",
      "capital" : "Singapore",
      "code" : "SG",
      "name" : "Singapore",
      "population" : 5638676,
      "population_density" : 8148.38,
      "flag" : {
        "emoji" : "🇸🇬",
        "emoji_unicode" : "U+1F1F8 U+1F1EC",
        "emojitwo" : "https://cdn.ipregistry.co/flags/emojitwo/sg.svg",
        "noto" : "https://cdn.ipregistry.co/flags/noto/sg.png",
        "twemoji" : "https://cdn.ipregistry.co/flags/twemoji/sg.svg",
        "wikimedia" : "https://cdn.ipregistry.co/flags/wikimedia/sg.svg"
      },
      "languages" : [ {
        "code" : "cmn",
        "name" : "cmn",
        "native" : "cmn"
      }, {
        "code" : "en",
        "name" : "English",
        "native" : "English"
      }, {
        "code" : "ms",
        "name" : "Malay",
        "native" : "Melayu"
      }, {
        "code" : "ta",
        "name" : "Tamil",
        "native" : "தமிழ்"
      }, {
        "code" : "zh",
        "name" : "Chinese",
        "native" : "中文"
      } ],
      "tld" : ".sg"
    },
    "region" : {
      "code" : null,
      "name" : "Singapore"
    },
    "city" : "Singapore",
    "postal" : "96534",
    "latitude" : 1.28967,
    "longitude" : 103.85007,
    "language" : {
      "code" : "cmn",
      "name" : "cmn",
      "native" : "cmn"
    },
    "in_eu" : false
  },
  "security" : {
    "is_bogon" : false,
    "is_cloud_provider" : false,
    "is_tor" : false,
    "is_tor_exit" : false,
    "is_proxy" : false,
    "is_anonymous" : false,
    "is_abuser" : false,
    "is_attacker" : false,
    "is_threat" : false
  },
  "time_zone" : {
    "id" : "Asia/Singapore",
    "abbreviation" : "SGT",
    "current_time" : "2019-09-29T23:13:32+08:00",
    "name" : "Singapore Standard Time",
    "offset" : 28800,
    "in_daylight_saving" : false
  }
}
Limitations:

Free plan includes 100,000 requests
Requires registration to get your API key



(15)ipstack (formerly freegeoip.net)
Try it: http://api.ipstack.com/<ip address>?access_key=<your api key>

$.getJSON('http://api.ipstack.com/<ip_address>?access_key=<your_api_key>', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
    "ip": "116.12.250.1",
    "type": "ipv4",
    "continent_code": "AS",
    "continent_name": "Asia",
    "country_code": "SG",
    "country_name": "Singapore",
    "region_code": "01",
    "region_name": "Central Singapore Community Development Council",
    "city": "Singapore",
    "zip": null,
    "latitude": 1.2931,
    "longitude": 103.8558,
    "location": {
        "geoname_id": 1880252,
        "capital": "Singapore",
        "languages": [{
            "code": "en",
            "name": "English",
            "native": "English"
        },
        {
            "code": "ms",
            "name": "Malay",
            "native": "Bahasa Melayu"
        },
        {
            "code": "ta",
            "name": "Tamil",
            "native": "\u0ba4\u0bae\u0bbf\u0bb4\u0bcd"
        },
        {
            "code": "zh",
            "name": "Chinese",
            "native": "\u4e2d\u6587"
        }],
        "country_flag": "http:\/\/assets.ipstack.com\/flags\/sg.svg",
        "country_flag_emoji": "\ud83c\uddf8\ud83c\uddec",
        "country_flag_emoji_unicode": "U+1F1F8 U+1F1EC",
        "calling_code": "65",
        "is_eu": false
    }
}
Limitations:

10,000 requests per month
Requires IP address parameter
Requires registration to get your API key
No SSL (https) with the free plan


(16)jsonip.com
Try it: https://jsonip.com

$.getJSON('https://jsonip.com/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip": "116.12.250.1",
  "about": "/about",
  "Pro!": "http://getjsonip.com",
  "reject-fascism": "Liberal America will prevail"
}
Limitations:

The response includes upsell and politics
JSON Test
Try it: http://ip.jsontest.com/

$.getJSON('http://ip.jsontest.com/?callback=?', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip": "116.12.250.1"
}
Limitations:

No SSL (https)
Goes down a lot (over quota), so I wouldn't use it for production
Returns IPv6 address if you have one, which may not be what you want



(17)Nekudo
Try it: https://geoip.nekudo.com/api

$.getJSON('https://geoip.nekudo.com/api', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "city": "Singapore",
  "country": {
    "name": "Singapore",
    "code": "SG"
  },
  "location": {
    "accuracy_radius": 50,
    "latitude": 1.2855,
    "longitude": 103.8565,
    "time_zone": "Asia/Singapore"
  },
  "ip": "116.12.250.1"
}
Limitations:

Blocked by ad blockers using the EasyPrivacy list



(18)SmartIP
Try it: https://api.smartip.io/?api_key=<your api key>

$.getJSON('https://api.smartip.io/?api_key=<your_api_key>', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "status-code": 200,
  "country": {
    "is-metric": true,
    "is-in-europe": false,
    "region-geo-id": null,
    "continent-geo-id": 6255147,
    "country-geo-id": 1880251,
    "region-code": null,
    "region-name": null,
    "continent-code": "AS",
    "continent-name": "Asia",
    "capital": "Singapur",
    "country-name": "Singapore",
    "country-two-letter-iso-code": "SG",
    "country-iso-code": "SG"
  },
  "location": {
    "metro-code": null,
    "longitude": 103.8547,
    "latitude": 1.2929,
    "timezone": "Asia/Singapore",
    "zip-code": null,
    "city": "Singapore"
  },
  "asn": {
    "organization": "SingNet",
    "asn": "AS3758"
  },
  "currency": {
    "native-name": "新币",
    "code": "SGD",
    "name": "Singapore Dollar",
    "symbol": "$"
  },
  "timezone": {
    "is-daylight-saving": false,
    "gmt-offset": 28800,
    "date-time": "2019-08-23T14:22:11+08:00",
    "microsoft-name": "Singapore Standard Time",
    "iana-name": "Asia/Singapore"
  },
  "security": {
    "is-crawler": false,
    "is-proxy": false,
    "is-tor": false,
    "tor-insights": null,
    "proxy-insights": null,
    "crawler-insights": null
  },
  "crypto": {
    "is-crypto-node": false,
    "crypto-insights": null
  },
  "user-agent": {
    "os": {
      "name": "Windows",
      "platform": "x64",
      "version": "10",
      "family": "Windows"
    },
    "device": {
      "brand": "",
      "model": "",
      "family": "desktop"
    },
    "engine-version": "",
    "engine": "Blink",
    "name": "Chrome",
    "type": "browser",
    "header": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36",
    "version": "76.0.3809.100",
    "family": "Chrome"
  },
  "error": null,
  "hostname": "116.12.250.1",
  "ip-type": "ipv4",
  "ip": "116.12.250.1"
}
Limitations:

250,000 requests per month
Requires registration to get your API key
Requires SSL (https)

No comments:

Post a Comment

Featured Post

[Solved] How to get current location of user using javascript?(Example code)

How to get the current location of a user using javascript? You might think to get a user's location is a difficult task, but it&...

Popular Posts