I need to somehow retrieve the client's IP address using JavaScript; no server side code, not even SSI.
However, I'm not against using a free 3rd party script/service.
This question is related to
javascript
jquery
ip-address
<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
<script>
function systemip(){
document.getElementById("ip").value = myip
console.log(document.getElementById("ip").value)
}
</script>
You can use the userinfo.io javascript library.
<script type="text/javascript" src="userinfo.0.0.1.min.js"></script>
UserInfo.getInfo(function(data) {
alert(data.ip_address);
}, function(err) {
// Do something with the error
});
You can also use requirejs to load the script.
It will give you the IP address of your visitor, as well as a few data on its location (country, city, etc.). It is based on maxmind geoip database.
Disclaimer: I wrote this library
Most of the answers here "work around" the need for server-side code by... Hitting someone else's server. Which is a totally valid technique, unless you actually do need to get the IP address without hitting a server.
Traditionally this wasn't possible without some sort of a plugin (and even then, you'd likely get the wrong IP address if you were behind a NAT router), but with the advent of WebRTC it is actually possible to do this... If you're targeting browsers that support WebRTC (currently: Firefox, Chrome and Opera).
Please read mido's answer for details on how you can retrieve useful client IP addresses using WebRTC.
<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
<script>
function systemip(){
document.getElementById("ip").value = myip
console.log(document.getElementById("ip").value)
}
</script>
Try this
$.get("http://ipinfo.io", function(response) {
alert(response.ip);
}, "jsonp");
OR
$(document).ready(function () {
$.getJSON("http://jsonip.com/?callback=?", function (data) {
console.log(data);
alert(data.ip);
});
});
I would say Chad and Malta has great answer. However, theirs are complicated. So I suggest this code that I found from ads by country plugin
<script>
<script language="javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="javascript">
mmjsCountryCode = geoip_country_code();
mmjsCountryName = geoip_country_name();
</script>
No ajax. Just plain javascripts. :D
If you go to http://j.maxmind.com/app/geoip.js you will see that it contains
function geoip_country_code() { return 'ID'; }
function geoip_country_name() { return 'Indonesia'; }
function geoip_city() { return 'Jakarta'; }
function geoip_region() { return '04'; }
function geoip_region_name() { return 'Jakarta Raya'; }
function geoip_latitude() { return '-6.1744'; }
function geoip_longitude() { return '106.8294'; }
function geoip_postal_code() { return ''; }
function geoip_area_code() { return ''; }
function geoip_metro_code() { return ''; }
It doesn't really answer the question yet because
http://j.maxmind.com/app/geoip.js doesn't contain the IP (although I bet it uses the IP to get the country).
But it's so easy to make a PhP script that pop something like
function visitorsIP() { return '123.123.123.123'; }
Make that. Put on http://yourdomain.com/yourip.php.
Then do
<script language="javascript" src="http://yourdomain.com/yourip.php"></script>
The question specifically mention NOT to use third party script. There is no other way. Javascript cannot know your IP. But other servers that can be accessed through javascript can which work just as well with no issue.
All the above answers have a server part, not pure client part. This should be provided by the web browser. At present, no web browser support this.
However, with this addon for firefox: https://addons.mozilla.org/en-US/firefox/addon/ip-address/ You will have to ask your users to install this addon. (it's good from me, a 3rd party).
you can test whether the user has installed it.
var installed=window.IP!==undefined;
you can get it with javascript, if it is installed, then var ip=IP.getClient(); var IPclient=ip.IP; //while ip.url is the url
ip=IP.getServer();
var IPserver=ip.IP;
var portServer=ip.port;
//while ip.url is the url
//or you can use IP.getBoth();
more information here: http://www.jackiszhp.info/tech/addon.IP.html
Well, I am digressing from the question, but I had a similar need today and though I couldn't find the ID from the client using Javascript, I did the following.
On the server side: -
<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>
Using Javascript
var ip = $get("uip").innerHTML;
I am using ASP.Net Ajax, but you can use getElementById instead of $get().
What's happening is, I've got a hidden div element on the page with the user's IP rendered from the server. Than in Javascript I just load that value.
This might be helpful to some people with a similar requirement like yours (like me while I hadn't figure this out).
Cheers!
There isn't really a reliable way to get the client computer's IP address.
This goes through some of the possibilities. The code that uses Java will break if the user has multiple interfaces.
http://nanoagent.blogspot.com/2006/09/how-to-find-evaluate-remoteaddrclients.html
From looking at the other answers here it sounds like you may want to get the client's public IP address, which is probably the address of the router they're using to connect to the internet. A lot of the other answers here talk about that. I would recommend creating and hosting your own server side page for receiving the request and responding with the IP address instead of depending on someone else's service that may or may not continue to work.
You can do an ajax call to hostip.info or a similar service...
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;
}
As a bonus, geolocalisation information is returned in the same call.
You can use web services like: http://ip-api.com/
Example:
<script type="text/javascript" src="http://ip-api.com/json/?callback=foo">
<script>
function foo(json) {
alert(json.query)
}
</script>
additional example: http://whatmyip.info
You can do an ajax call to hostip.info or a similar service...
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;
}
As a bonus, geolocalisation information is returned in the same call.
Try this: http://httpbin.org/ip (or https://httpbin.org/ip)
Example with https:
$.getJSON('https://httpbin.org/ip', function(data) {
console.log(data['origin']);
});
Source: http://httpbin.org/
Not possible in general unless you use some kind of external service.
You can, relaying it via server side with JSONP
And while googling to find one, found it here on SO Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>
Note : The telize.com API has permanently shut down as of November 15th, 2015.
Use ipdata.co.
The API also provides geolocation data and has 10 global endpoints each able to handle >800M requests a day!
This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
$("#response").html(response.ip);_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<pre id="response"></pre>
_x000D_
You can't. You'd have to ask a server.
<script type="application/javascript">
function getip(json)
{
alert(json.ip);
}
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
Run above script Clik here
It can't be done with Javascript alone (unless the clients have a browser plugin as described above). It can't be done with Flash on the client either. But it can be done on the client using a Java applet (and javascript can talk to that), although it will prompt for full permissions. e.g. See http://www.findmyrouter.net
You could do this entirely client side and mostly in JavaScript by using a Flash object that the js can call. Flash can access the IP address of the local machine which might not be very useful.
You can, relaying it via server side with JSONP
And while googling to find one, found it here on SO Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?
<script type="application/javascript">
function getip(json){
alert(json.ip); // alerts the ip address
}
</script>
<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>
Note : The telize.com API has permanently shut down as of November 15th, 2015.
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. If you know of any more, then please add a comment and I'll update this answer.
Try it: https://ipgeolocation.abstractapi.com/v1/?api_key=<your_api_key>
$.getJSON('https://ipgeolocation.abstractapi.com/v1/?api_key=<your_api_key>', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Returns:
{
"ip_address": "116.12.250.1",
"city": "Singapore (Queenstown Estate)",
"city_geoname_id": 1884386,
"region": null,
"region_iso_code": null,
"region_geoname_id": null,
"postal_code": null,
"country": "Singapore",
"country_code": "SG",
"country_geoname_id": 1880251,
"country_is_eu": false,
"continent": "Asia",
"continent_code": "AS",
"continent_geoname_id": 6255147,
"longitude": 103.807,
"latitude": 1.29199,
"timezone": {
"name": "Asia/Singapore",
"abbreviation": "+08",
"gmt_offset": 8,
"current_time": "22:33:13",
"is_dst": false
},
"flag": {
"emoji": "",
"unicode": "U+1F1F8 U+1F1EC",
"png": "https://static.abstractapi.com/country-flags/SG_flag.png",
"svg": "https://static.abstractapi.com/country-flags/SG_flag.svg"
},
"connection": {
"autonomous_system_number": 3758,
"autonomous_system_organization": "SingNet Pte Ltd",
"connection_type": "Corporate",
"isp_name": "SingNet Pte Ltd",
"organizaton_name": "Singapore Post LTD"
}
}
Limitations:
Try it: https://api.astroip.co/116.12.250.1/?api_key=<your_api_key>
$.getJSON('https://api.astroip.co/116.12.250.1/?api_key=<your_api_key>', function(data) {
console.log(JSON.stringify(data, null, 2));
});
Returns:
{
"status-code": 200,
"geo": {
"is-metric": true,
"is-in-europe": false,
"longitude": 103.7601,
"latitude": 1.3125,
"country-geo-id": 1880251,
"zip-code": "12",
"city": "Singapore",
"region-code": null,
"region-name": null,
"continent-code": "AS",
"continent-name": "Asia",
"capital": "Singapur",
"country-name": "Singapore",
"country-iso-code": "SG"
},
"asn": {
"route": "116.12.240.0/20",
"name": "SINGNET",
"type": "business",
"domain": "singtel.com",
"organization": "SingNet",
"asn": "AS3758"
},
"currency": {
"native-name": "????",
"code": "SGD",
"name": "Singapore Dollar",
"symbol": "$"
},
"timezone": {
"is-daylight-saving": false,
"gmt-offset": 28800,
"date-time": "2020-11-12T15:28:45+08:00",
"microsoft-name": "Asia/Singapore",
"iana-name": "Asia/Singapore"
},
"security": {
"is-crawler": false,
"is-proxy": false,
"is-tor": false,
"tor-insights": null,
"proxy-insights": null,
"crawler-insights": null
},
"crypto": null,
"user-agent": null,
"error": null,
"hostname": "116.12.250.1",
"ip-type": "ipv4",
"ip": "116.12.250.1"
}
Limitations:
Try it: https://www.cloudflare.com/cdn-cgi/trace
// If your site is on Cloudflare, then you can use '/cdn-cgi/trace' instead
$.get('https://www.cloudflare.com/cdn-cgi/trace', function(data) {
console.log(data)
})
Returns:
fl=4f422
h=www.cloudflare.com
ip=54.193.27.106
ts=1575967108.245
visit_scheme=https
uag=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36 Hypothesis-Via
colo=SJC
http=http/1.1
loc=US
tls=TLSv1.3
sni=plaintext
warp=off
Limitations:
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:
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:
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:
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": "$",
"geoplugin_currencySymbol_UTF8": "$",
"geoplugin_currencyConverter": 1.4239
}
Limitations:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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": "https://jsonip.com/about",
"Pro!": "http://getjsonip.com",
"Get Notifications": "https://jsonip.com/notify"
}
Limitations:
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:
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:
Keep in mind that since these are all free services, your mileage may vary in terms of exceeding quota
I really like api.ipify.org
because it supports both HTTP and HTTPS.
Here are some examples of getting the IP using api.ipify.org
using jQuery.
https://api.ipify.org?format=json
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
alert(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
http://api.ipify.org?format=json
$.getJSON("http://api.ipify.org/?format=json", function(e) {_x000D_
alert(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
If you don't want it in JSON there is also a plaintext response over HTTPS
https://api.ipify.org
And there is also a plaintext response over HTTP
http://api.ipify.org
Java Script to find IP
To get the IP Address I am making a JSON call to the Free Web Service. like
[jsonip.com/json, ipinfo.io/json, www.telize.com/geoip, ip-api.com/json, api.hostip.info/get_json.php]
and I am passing the name of the callback function which will be called on completion of the request.
<script type="text/javascript">
window.onload = function () {
var webService = "http://www.telize.com/geoip";
var script = document.createElement("script");
script.type = "text/javascript";
script.src = webService+"?callback=MyIP";
document.getElementsByTagName("head")[0].appendChild(script);
};
function MyIP(response) {
document.getElementById("ipaddress").innerHTML = "Your IP Address is " + response.ip;
}
</script>
<body>
<form>
<span id = "ipaddress"></span>
</form>
</body>
for xml response code
WebRTC which doesn't require server support.
There's an easier and free approach that won't ask your visitor for any permission.
It consists in submitting a very simple Ajax POST request to http://freegeoip.net/json. Once you receive your location information, in JSON, you react accordingly by updating the page or redirecting to a new one.
Here is how you submit your request for location information:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
console.log(location)
}
} );
I'm no javascript guru, but if its possible you could open an iframe with http://www.whatismyip.com/automation/n09230945.asp as the source and read the content of the frame.
Edit: this wont work because of the cross domain security.
You can use the api service from telize
If you need just the public ip of client, do this :
var ip = "http://www.telize.com/ip";
var response = http.request({url: ip});
and if you want more details like location and stuff, you can do this :
var ipAndGeoDetails = "http://www.telize.com/geoip/"
var response = http.request({url: ipAndGeoDetails});
NOTE : The public API of telize will permanently shut down on November 15th, 2015.
As shown recently by a new Github repository, webrtc-ip, you can now leak a user's public IP address using WebRTC. Sadly, this leak does not work for private IPs, due to the gradual shift to mDNS (at least for WebRTC), completely explained here. However, here's a working demo:
getIPs().then(res => document.write(res.join('\n')))
_x000D_
<script src="https://cdn.jsdelivr.net/gh/joeymalvinni/webrtc-ip/dist/bundle.dev.js"></script>
_x000D_
The compiled source code for this repository can be found here.
(Previously) Final Update
This solution would not longer work because browsers are fixing webrtc leak: for more info on that read this other question: RTCIceCandidate no longer returning IP
Update: I always wanted to make a min/ uglified version of the code, so here is an ES6 Promise code:
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))
_x000D_
Note: This new minified code would return only single IP if you want all the IPs of the user( which might be more depending on his network), use the original code...
thanks to WebRTC, it is very easy to get local IP in WebRTC supported browsers( at least for now). I have modified the source code, reduced the lines, not making any stun requests since you only want Local IP, not the Public IP, the below code works in latest Firefox and Chrome, just run the snippet and check for yourself:
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);
_x000D_
<h1> Demo retrieving Client IP using WebRTC </h1>
_x000D_
what is happening here is, we are creating a dummy peer connection, and for the remote peer to contact us, we generally exchange ice candidates with each other. And reading the ice candidates( from local session description and onIceCandidateEvent) we can tell the IP of the user.
where I took code from --> Source
The simple solution to get the ip address is add the following code in your file.
$.getJSON('https://api.ipify.org?format=json', function(data){
// Your callback functions like
console.log(data.ip);
localStorage.setItem('ip',data.ip);
alert(data.ip);
});
It will get the ip address when page loads.
One problem with some of the other services I've seen here is that they either do not support IPv6, or they act unpredictably in the presence of IPv6.
Because I needed this capability myself in a dual stack environment, I put together my own IP address service, which you can find at http://myip.addr.space/ . There's also a quick reference at /help.
To use it with jQuery, use the /ip
endpoint. You will get back plain text containing the IP address, depending on the subdomain you use:
$.get("http://myip.addr.space/ip")
returns either IPv6 or IPv4, depending on what is available to the system. (JSFiddle)
$.get("http://ipv4.myip.addr.space/ip")
always returns IPv4 (or fails if no IPv4).
$.get("http://ipv6.myip.addr.space/ip")
always returns IPv6 (or fails if no IPv6).
Well, if in the HTML you import a script...
<script type="text/javascript" src="//stier.linuxfaq.org/ip.php"></script>
You can then use the variable userIP (which would be the visitor's IP address) anywhere on the page.
To redirect:
<script>
if (userIP == "555.555.555.55") {window.location.replace("http://192.168.1.3/flex-start/examples/navbar-fixed-top/");}
</script>
Or to show it on the page: document.write (userIP);
DISCLAIMER: I am the author of the script I said to import. The script comes up with the IP by using PHP. The source code of the script is below.
<?php
//Gets the IP address
$ip = getenv("REMOTE_ADDR") ;
Echo "var userIP = '" . $ip . "';";
?>
Include this code in your page : <script type="text/javascript" src="http://l2.io/ip.js"></script>
more doc here
Not possible in general unless you use some kind of external service.
You can use web services like: http://ip-api.com/
Example:
<script type="text/javascript" src="http://ip-api.com/json/?callback=foo">
<script>
function foo(json) {
alert(json.query)
}
</script>
additional example: http://whatmyip.info
Get System Local IP:
try {
var RTCPeerConnection = window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({ iceServers: [] });
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', { reliable: false });
};
rtc.onicecandidate = function (evt) {
if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
LgIpDynAdd = displayAddrs.join(" or perhaps ") || "n/a";
alert(LgIpDynAdd)
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
alert(addr);
}
});
}
})();} catch (ex) { }
$.getJSON("http://jsonip.com?callback=?", function (data) {
alert("Your ip: " + data.ip);
});
With using Smart-IP.net Geo-IP API. For example, by using jQuery:
$(document).ready( function() {
$.getJSON( "http://smart-ip.net/geoip-json?callback=?",
function(data){
alert( data.host);
}
);
});
You can try using our https://ip-api.io geo ip API. For example with jQuery:
$(document).ready( function() {
$.getJSON("http://ip-api.io/api/json",
function(data){
console.log(data);
}
);
});
Also https://ip-api.io checks TOR, public proxy and spammer databases and provides this information as well.
Example response:
{
"ip": "182.35.213.213",
"country_code": "US",
"country_name": "United States",
"region_code": "CA",
"region_name": "California",
"city": "San Francisco",
"zip_code": "94107",
"time_zone": "America/Los_Angeles",
"latitude": 32.7697,
"longitude": -102.3933,
"suspicious_factors": {
"is_proxy": true,
"is_tor_node": true,
"is_spam": true,
"is_suspicious": true // true if any of other fields (is_proxy, is_tor_node, is_spam) is true
}
}
As shown recently by a new Github repository, webrtc-ip, you can now leak a user's public IP address using WebRTC. Sadly, this leak does not work for private IPs, due to the gradual shift to mDNS (at least for WebRTC), completely explained here. However, here's a working demo:
getIPs().then(res => document.write(res.join('\n')))
_x000D_
<script src="https://cdn.jsdelivr.net/gh/joeymalvinni/webrtc-ip/dist/bundle.dev.js"></script>
_x000D_
The compiled source code for this repository can be found here.
(Previously) Final Update
This solution would not longer work because browsers are fixing webrtc leak: for more info on that read this other question: RTCIceCandidate no longer returning IP
Update: I always wanted to make a min/ uglified version of the code, so here is an ES6 Promise code:
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))
_x000D_
Note: This new minified code would return only single IP if you want all the IPs of the user( which might be more depending on his network), use the original code...
thanks to WebRTC, it is very easy to get local IP in WebRTC supported browsers( at least for now). I have modified the source code, reduced the lines, not making any stun requests since you only want Local IP, not the Public IP, the below code works in latest Firefox and Chrome, just run the snippet and check for yourself:
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);
_x000D_
<h1> Demo retrieving Client IP using WebRTC </h1>
_x000D_
what is happening here is, we are creating a dummy peer connection, and for the remote peer to contact us, we generally exchange ice candidates with each other. And reading the ice candidates( from local session description and onIceCandidateEvent) we can tell the IP of the user.
where I took code from --> Source
Check out http://www.ipify.org/
According to them:
- You can use it without limit (even if you're doing millions of requests per minute).
- ipify is completely open source (check out the GitHub repository).
Here's a working JS example (instead of wondering why this answer has so few votes, try it yourself to see it in action):
<script>
function getIP(json) {
alert("My public IP address is: " + json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
Too lazy to copy/paste? I like it. Here's a demo
Too lazy to click? :O
Note: Turn off Adblock Plus / uBlock & co before running the demo .. otherwise, it just won't work.
I have nothing to do with the IPify team. I just think it's ridiculously cool that someone would provide such a service for the general good.
Java Script to find IP
To get the IP Address I am making a JSON call to the Free Web Service. like
[jsonip.com/json, ipinfo.io/json, www.telize.com/geoip, ip-api.com/json, api.hostip.info/get_json.php]
and I am passing the name of the callback function which will be called on completion of the request.
<script type="text/javascript">
window.onload = function () {
var webService = "http://www.telize.com/geoip";
var script = document.createElement("script");
script.type = "text/javascript";
script.src = webService+"?callback=MyIP";
document.getElementsByTagName("head")[0].appendChild(script);
};
function MyIP(response) {
document.getElementById("ipaddress").innerHTML = "Your IP Address is " + response.ip;
}
</script>
<body>
<form>
<span id = "ipaddress"></span>
</form>
</body>
for xml response code
WebRTC which doesn't require server support.
$.getJSON("http://jsonip.com?callback=?", function (data) {
alert("Your ip: " + data.ip);
});
If you use NGINX somewhere, you can add this snippet and ask your own server via any AJAX tool.
location /get_ip {
default_type text/plain;
return 200 $remote_addr;
}
var call_to = "http://smart-ip.net/geoip-json?callback=?";
$.getJSON(call_to, function(data){
alert(data.host);
});
data.host
is the ip address. Simply call this from your browser.
http://smart-ip.net/geoip-json?callback=?
[Without quotes] and get the ip.
Try this
$.get("http://ipinfo.io", function(response) {
alert(response.ip);
}, "jsonp");
I'm going to offer a method that I use a lot when I want to store information in the html page, and want my javascript to read information without actually having to pass parameters to the javascript. This is especially useful when your script is referenced externally, rather than inline.
It doesn't meet the criterion of "no server side script", however. But if you can include server side scripting in your html, do this:
Make hidden label elements at the bottom of your html page, just above the end body tag.
Your label will look like this:
<label id="ip" class="hiddenlabel"><?php echo $_SERVER['REMOTE_ADDR']; ?></label>
Be sure to make a class called hiddenlabel
and set the visibility:hidden
so no one actually sees the label. You can store lots of things this way, in hidden labels.
Now, in your javascript, to retrieve the information stored in the label (in this case the client's ip address), you can do this:
var ip = document.getElementById("ip").innerHTML;
Now your variable "ip" equals the ip address. Now you can pass the ip to your API request.
* EDIT 2 YEARS LATER * Two minor refinements:
I routinely use this method, but call the label class="data"
, because, in fact, it is a way to store data. Class name "hiddenlabel" is kind of a stupid name.
The second modification is in the style sheet, instead of visibility:hidden
:
.data{
display:none;
}
...is the better way of doing it.
There isn't really a reliable way to get the client computer's IP address.
This goes through some of the possibilities. The code that uses Java will break if the user has multiple interfaces.
http://nanoagent.blogspot.com/2006/09/how-to-find-evaluate-remoteaddrclients.html
From looking at the other answers here it sounds like you may want to get the client's public IP address, which is probably the address of the router they're using to connect to the internet. A lot of the other answers here talk about that. I would recommend creating and hosting your own server side page for receiving the request and responding with the IP address instead of depending on someone else's service that may or may not continue to work.
Most of the answers here "work around" the need for server-side code by... Hitting someone else's server. Which is a totally valid technique, unless you actually do need to get the IP address without hitting a server.
Traditionally this wasn't possible without some sort of a plugin (and even then, you'd likely get the wrong IP address if you were behind a NAT router), but with the advent of WebRTC it is actually possible to do this... If you're targeting browsers that support WebRTC (currently: Firefox, Chrome and Opera).
Please read mido's answer for details on how you can retrieve useful client IP addresses using WebRTC.
Appspot.com callback's service isn't available. ipinfo.io seems to be working.
I did an extra step and retrieved all geo info using AngularJS. (Thanks to Ricardo) Check it out.
<div ng-controller="geoCtrl">
<p ng-bind="ip"></p>
<p ng-bind="hostname"></p>
<p ng-bind="loc"></p>
<p ng-bind="org"></p>
<p ng-bind="city"></p>
<p ng-bind="region"></p>
<p ng-bind="country"></p>
<p ng-bind="phone"></p>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.12/angular-route.min.js"></script>
<script>
'use strict';
var geo = angular.module('geo', [])
.controller('geoCtrl', ['$scope', '$http', function($scope, $http) {
$http.jsonp('http://ipinfo.io/?callback=JSON_CALLBACK')
.success(function(data) {
$scope.ip = data.ip;
$scope.hostname = data.hostname;
$scope.loc = data.loc; //Latitude and Longitude
$scope.org = data.org; //organization
$scope.city = data.city;
$scope.region = data.region; //state
$scope.country = data.country;
$scope.phone = data.phone; //city area code
});
}]);
</script>
Working page here: http://www.orangecountyseomarketing.com/projects/_ip_angularjs.html
<script type="application/javascript">
function getip(json)
{
alert(json.ip);
}
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>
Run above script Clik here
Try this
$.get("http://ipinfo.io", function(response) {
alert(response.ip);
}, "jsonp");
OR
$(document).ready(function () {
$.getJSON("http://jsonip.com/?callback=?", function (data) {
console.log(data);
alert(data.ip);
});
});
I would say Chad and Malta has great answer. However, theirs are complicated. So I suggest this code that I found from ads by country plugin
<script>
<script language="javascript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="javascript">
mmjsCountryCode = geoip_country_code();
mmjsCountryName = geoip_country_name();
</script>
No ajax. Just plain javascripts. :D
If you go to http://j.maxmind.com/app/geoip.js you will see that it contains
function geoip_country_code() { return 'ID'; }
function geoip_country_name() { return 'Indonesia'; }
function geoip_city() { return 'Jakarta'; }
function geoip_region() { return '04'; }
function geoip_region_name() { return 'Jakarta Raya'; }
function geoip_latitude() { return '-6.1744'; }
function geoip_longitude() { return '106.8294'; }
function geoip_postal_code() { return ''; }
function geoip_area_code() { return ''; }
function geoip_metro_code() { return ''; }
It doesn't really answer the question yet because
http://j.maxmind.com/app/geoip.js doesn't contain the IP (although I bet it uses the IP to get the country).
But it's so easy to make a PhP script that pop something like
function visitorsIP() { return '123.123.123.123'; }
Make that. Put on http://yourdomain.com/yourip.php.
Then do
<script language="javascript" src="http://yourdomain.com/yourip.php"></script>
The question specifically mention NOT to use third party script. There is no other way. Javascript cannot know your IP. But other servers that can be accessed through javascript can which work just as well with no issue.
Try this: http://httpbin.org/ip (or https://httpbin.org/ip)
Example with https:
$.getJSON('https://httpbin.org/ip', function(data) {
console.log(data['origin']);
});
Source: http://httpbin.org/
First of all the actual answer: It is not possible to use purely client-side executed code to find out your own IP address.
However you can just do a GET towards https://api.muctool.de/whois and receive something like to obtain a client's IP address
{
"ip": "88.217.152.15",
"city": "Munich",
"isp": "M-net Telekommunikations GmbH",
"country": "Germany",
"countryIso": "DE",
"postalCode": "80469",
"subdivisionIso": "BY",
"timeZone": "Europe/Berlin",
"cityGeonameId": 2867714,
"countryGeonameId": 2921044,
"subdivisionGeonameId": 2951839,
"ispId": 8767,
"latitude": 48.1299,
"longitude": 11.5732,
"fingerprint": "61c5880ee234d66bded68be14c0f44236f024cc12efb6db56e4031795f5dc4c4",
"session": "69c2c032a88fcd5e9d02d0dd6a5080e27d5aafc374a06e51a86fec101508dfd3",
"fraud": 0.024,
"tor": false
}
I'm no javascript guru, but if its possible you could open an iframe with http://www.whatismyip.com/automation/n09230945.asp as the source and read the content of the frame.
Edit: this wont work because of the cross domain security.
Javascript / jQuery get Client's IP Address & Location (Country, City)
You only need to embed a tag with "src" link to the server. The server will return "codehelper_ip" as an Object / JSON, and you can use it right away.
// First, embed this script in your head or at bottom of the page.
<script language="Javascript" src="http://www.codehelper.io/api/ips/?js"></script>
// You can use it
<script language="Javascript">
alert(codehelper_ip.IP);
alert(codehelper_ip.Country);
</script>
More information at Javascript Detect Real IP Address Plus Country
If you are using jQUery, you can try:
console.log(codehelper_ip);
It will show you more information about returned object.
If you want callback function, please try this:
// First, embed this script in your head or at bottom of the page.
<script language="Javascript" src="http://www.codehelper.io/api/ips/?callback=yourcallback"></script>
// You can use it
<script language="Javascript">
function yourcallback(json) {
alert(json.IP);
}
</script>
<!DOCTYPE html>
<html ng-app="getIp">
<body>
<div ng-controller="getIpCtrl">
<div ng-bind="ip"></div>
</div>
<!-- Javascript for load faster
================================================== -->
<script src="lib/jquery/jquery.js"></script>
<script src="lib/angular/angular.min.js"></script>
<script>
/// Scripts app
'use strict';
/* App Module */
var getIp = angular.module('getIp', [ ]);
getIp.controller('getIpCtrl', ['$scope', '$http',
function($scope, $http) {
$http.jsonp('http://jsonip.appspot.com/?callback=JSON_CALLBACK')
.success(function(data) {
$scope.ip = data.ip;
});
}]);
</script>
</body>
</html>
$.getJSON("http://jsonip.com?callback=?", function (data) {
alert("Your ip address: " + data.ip);
});
Well, I am digressing from the question, but I had a similar need today and though I couldn't find the ID from the client using Javascript, I did the following.
On the server side: -
<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>
Using Javascript
var ip = $get("uip").innerHTML;
I am using ASP.Net Ajax, but you can use getElementById instead of $get().
What's happening is, I've got a hidden div element on the page with the user's IP rendered from the server. Than in Javascript I just load that value.
This might be helpful to some people with a similar requirement like yours (like me while I hadn't figure this out).
Cheers!
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); });
Use ipdata.co.
The API also provides geolocation data and has 10 global endpoints each able to handle >800M requests a day!
This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.
$.get("https://api.ipdata.co?api-key=test", function (response) {_x000D_
$("#response").html(response.ip);_x000D_
}, "jsonp");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<pre id="response"></pre>
_x000D_
Check out http://www.ipify.org/
According to them:
- You can use it without limit (even if you're doing millions of requests per minute).
- ipify is completely open source (check out the GitHub repository).
Here's a working JS example (instead of wondering why this answer has so few votes, try it yourself to see it in action):
<script>
function getIP(json) {
alert("My public IP address is: " + json.ip);
}
</script>
<script src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
Too lazy to copy/paste? I like it. Here's a demo
Too lazy to click? :O
Note: Turn off Adblock Plus / uBlock & co before running the demo .. otherwise, it just won't work.
I have nothing to do with the IPify team. I just think it's ridiculously cool that someone would provide such a service for the general good.
Most of the answers here "work around" the need for server-side code by... Hitting someone else's server. Which is a totally valid technique, unless you actually do need to get the IP address without hitting a server.
Traditionally this wasn't possible without some sort of a plugin (and even then, you'd likely get the wrong IP address if you were behind a NAT router), but with the advent of WebRTC it is actually possible to do this... If you're targeting browsers that support WebRTC (currently: Firefox, Chrome and Opera).
Please read mido's answer for details on how you can retrieve useful client IP addresses using WebRTC.
Well, I am digressing from the question, but I had a similar need today and though I couldn't find the ID from the client using Javascript, I did the following.
On the server side: -
<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>
Using Javascript
var ip = $get("uip").innerHTML;
I am using ASP.Net Ajax, but you can use getElementById instead of $get().
What's happening is, I've got a hidden div element on the page with the user's IP rendered from the server. Than in Javascript I just load that value.
This might be helpful to some people with a similar requirement like yours (like me while I hadn't figure this out).
Cheers!
There are two interpretations to this question. Most folks interpreted "Client IP" to mean the Public IP Address that Web server's see outside the LAN and out on the Internet. This is not the IP address of the client computer in most cases, though
I needed the real IP address of the computer that is running the browser that is hosting my JavaScript software (which is almost always a local IP address on a LAN that is behind something that NAT layer).
Mido posted a FANTASTIC answer, above, that seems to be the only answer that really provided the IP address of the client.
Thanks for that, Mido!
However, the function presented runs asynchronously. I need to actually USE the IP address in my code, and with an asynchronous solution, I might try to use the IP address before it is retrieved/learned/stored. I had to be able to wait on the results to arrive before using them.
Here is a "Waitable" version of Mido's function. I hope it helps someone else:
function findIP(onNewIP) { // onNewIp - your listener function for new IPs_x000D_
var promise = new Promise(function (resolve, reject) {_x000D_
try {_x000D_
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome_x000D_
var pc = new myPeerConnection({ iceServers: [] }),_x000D_
noop = function () { },_x000D_
localIPs = {},_x000D_
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,_x000D_
key;_x000D_
function ipIterate(ip) {_x000D_
if (!localIPs[ip]) onNewIP(ip);_x000D_
localIPs[ip] = true;_x000D_
}_x000D_
pc.createDataChannel(""); //create a bogus data channel_x000D_
pc.createOffer(function (sdp) {_x000D_
sdp.sdp.split('\n').forEach(function (line) {_x000D_
if (line.indexOf('candidate') < 0) return;_x000D_
line.match(ipRegex).forEach(ipIterate);_x000D_
});_x000D_
pc.setLocalDescription(sdp, noop, noop);_x000D_
}, noop); // create offer and set local description_x000D_
_x000D_
pc.onicecandidate = function (ice) { //listen for candidate events_x000D_
if (ice && ice.candidate && ice.candidate.candidate && ice.candidate.candidate.match(ipRegex)) {_x000D_
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);_x000D_
}_x000D_
resolve("FindIPsDone");_x000D_
return;_x000D_
};_x000D_
}_x000D_
catch (ex) {_x000D_
reject(Error(ex));_x000D_
}_x000D_
});// New Promise(...{ ... });_x000D_
return promise;_x000D_
};_x000D_
_x000D_
//This is the callback that gets run for each IP address found_x000D_
function foundNewIP(ip) {_x000D_
if (typeof window.ipAddress === 'undefined')_x000D_
{_x000D_
window.ipAddress = ip;_x000D_
}_x000D_
else_x000D_
{_x000D_
window.ipAddress += " - " + ip;_x000D_
}_x000D_
}_x000D_
_x000D_
//This is How to use the Waitable findIP function, and react to the_x000D_
//results arriving_x000D_
var ipWaitObject = findIP(foundNewIP); // Puts found IP(s) in window.ipAddress_x000D_
ipWaitObject.then(_x000D_
function (result) {_x000D_
alert ("IP(s) Found. Result: '" + result + "'. You can use them now: " + window.ipAddress)_x000D_
},_x000D_
function (err) {_x000D_
alert ("IP(s) NOT Found. FAILED! " + err)_x000D_
}_x000D_
);_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<h1>Demo "Waitable" Client IP Retrieval using WebRTC </h1>
_x000D_
Not possible in general unless you use some kind of external service.
If you're including an file anways, you could do a simple ajax get:
function ip_callback() {
$.get("ajax.getIp.php",function(data){ return data; }
}
And ajax.getIp.php
would be this:
<?=$_SERVER['REMOTE_ADDR']?>
Not possible in general unless you use some kind of external service.
Well, I am digressing from the question, but I had a similar need today and though I couldn't find the ID from the client using Javascript, I did the following.
On the server side: -
<div style="display:none;visibility:hidden" id="uip"><%= Request.UserHostAddress %></div>
Using Javascript
var ip = $get("uip").innerHTML;
I am using ASP.Net Ajax, but you can use getElementById instead of $get().
What's happening is, I've got a hidden div element on the page with the user's IP rendered from the server. Than in Javascript I just load that value.
This might be helpful to some people with a similar requirement like yours (like me while I hadn't figure this out).
Cheers!
With using Smart-IP.net Geo-IP API. For example, by using jQuery:
$(document).ready( function() {
$.getJSON( "http://smart-ip.net/geoip-json?callback=?",
function(data){
alert( data.host);
}
);
});
var call_to = "http://smart-ip.net/geoip-json?callback=?";
$.getJSON(call_to, function(data){
alert(data.host);
});
data.host
is the ip address. Simply call this from your browser.
http://smart-ip.net/geoip-json?callback=?
[Without quotes] and get the ip.
You can't. You'd have to ask a server.
There isn't really a reliable way to get the client computer's IP address.
This goes through some of the possibilities. The code that uses Java will break if the user has multiple interfaces.
http://nanoagent.blogspot.com/2006/09/how-to-find-evaluate-remoteaddrclients.html
From looking at the other answers here it sounds like you may want to get the client's public IP address, which is probably the address of the router they're using to connect to the internet. A lot of the other answers here talk about that. I would recommend creating and hosting your own server side page for receiving the request and responding with the IP address instead of depending on someone else's service that may or may not continue to work.
Javascript / jQuery get Client's IP Address & Location (Country, City)
You only need to embed a tag with "src" link to the server. The server will return "codehelper_ip" as an Object / JSON, and you can use it right away.
// First, embed this script in your head or at bottom of the page.
<script language="Javascript" src="http://www.codehelper.io/api/ips/?js"></script>
// You can use it
<script language="Javascript">
alert(codehelper_ip.IP);
alert(codehelper_ip.Country);
</script>
More information at Javascript Detect Real IP Address Plus Country
If you are using jQUery, you can try:
console.log(codehelper_ip);
It will show you more information about returned object.
If you want callback function, please try this:
// First, embed this script in your head or at bottom of the page.
<script language="Javascript" src="http://www.codehelper.io/api/ips/?callback=yourcallback"></script>
// You can use it
<script language="Javascript">
function yourcallback(json) {
alert(json.IP);
}
</script>
First of all the actual answer: It is not possible to use purely client-side executed code to find out your own IP address.
However you can just do a GET towards https://api.muctool.de/whois and receive something like to obtain a client's IP address
{
"ip": "88.217.152.15",
"city": "Munich",
"isp": "M-net Telekommunikations GmbH",
"country": "Germany",
"countryIso": "DE",
"postalCode": "80469",
"subdivisionIso": "BY",
"timeZone": "Europe/Berlin",
"cityGeonameId": 2867714,
"countryGeonameId": 2921044,
"subdivisionGeonameId": 2951839,
"ispId": 8767,
"latitude": 48.1299,
"longitude": 11.5732,
"fingerprint": "61c5880ee234d66bded68be14c0f44236f024cc12efb6db56e4031795f5dc4c4",
"session": "69c2c032a88fcd5e9d02d0dd6a5080e27d5aafc374a06e51a86fec101508dfd3",
"fraud": 0.024,
"tor": false
}
Get System Local IP:
try {
var RTCPeerConnection = window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
if (RTCPeerConnection) (function () {
var rtc = new RTCPeerConnection({ iceServers: [] });
if (1 || window.mozRTCPeerConnection) {
rtc.createDataChannel('', { reliable: false });
};
rtc.onicecandidate = function (evt) {
if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
};
rtc.createOffer(function (offerDesc) {
grepSDP(offerDesc.sdp);
rtc.setLocalDescription(offerDesc);
}, function (e) { console.warn("offer failed", e); });
var addrs = Object.create(null);
addrs["0.0.0.0"] = false;
function updateDisplay(newAddr) {
if (newAddr in addrs) return;
else addrs[newAddr] = true;
var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
LgIpDynAdd = displayAddrs.join(" or perhaps ") || "n/a";
alert(LgIpDynAdd)
}
function grepSDP(sdp) {
var hosts = [];
sdp.split('\r\n').forEach(function (line) {
if (~line.indexOf("a=candidate")) {
var parts = line.split(' '),
addr = parts[4],
type = parts[7];
if (type === 'host') updateDisplay(addr);
} else if (~line.indexOf("c=")) {
var parts = line.split(' '),
addr = parts[2];
alert(addr);
}
});
}
})();} catch (ex) { }
$.getJSON("http://jsonip.com?callback=?", function (data) {
alert("Your ip address: " + data.ip);
});
You can use my service http://ipinfo.io for this, which will give you the client IP, hostname, geolocation information and network owner. Here's a simple example that logs the IP:
$.get("http://ipinfo.io", function(response) {
console.log(response.ip);
}, "jsonp");
Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/
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); });
You could do this entirely client side and mostly in JavaScript by using a Flash object that the js can call. Flash can access the IP address of the local machine which might not be very useful.
There's an easier and free approach that won't ask your visitor for any permission.
It consists in submitting a very simple Ajax POST request to http://freegeoip.net/json. Once you receive your location information, in JSON, you react accordingly by updating the page or redirecting to a new one.
Here is how you submit your request for location information:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
console.log(location)
}
} );
If you're including an file anways, you could do a simple ajax get:
function ip_callback() {
$.get("ajax.getIp.php",function(data){ return data; }
}
And ajax.getIp.php
would be this:
<?=$_SERVER['REMOTE_ADDR']?>
The simple solution to get the ip address is add the following code in your file.
$.getJSON('https://api.ipify.org?format=json', function(data){
// Your callback functions like
console.log(data.ip);
localStorage.setItem('ip',data.ip);
alert(data.ip);
});
It will get the ip address when page loads.
You can use the api service from telize
If you need just the public ip of client, do this :
var ip = "http://www.telize.com/ip";
var response = http.request({url: ip});
and if you want more details like location and stuff, you can do this :
var ipAndGeoDetails = "http://www.telize.com/geoip/"
var response = http.request({url: ipAndGeoDetails});
NOTE : The public API of telize will permanently shut down on November 15th, 2015.
I'm going to offer a method that I use a lot when I want to store information in the html page, and want my javascript to read information without actually having to pass parameters to the javascript. This is especially useful when your script is referenced externally, rather than inline.
It doesn't meet the criterion of "no server side script", however. But if you can include server side scripting in your html, do this:
Make hidden label elements at the bottom of your html page, just above the end body tag.
Your label will look like this:
<label id="ip" class="hiddenlabel"><?php echo $_SERVER['REMOTE_ADDR']; ?></label>
Be sure to make a class called hiddenlabel
and set the visibility:hidden
so no one actually sees the label. You can store lots of things this way, in hidden labels.
Now, in your javascript, to retrieve the information stored in the label (in this case the client's ip address), you can do this:
var ip = document.getElementById("ip").innerHTML;
Now your variable "ip" equals the ip address. Now you can pass the ip to your API request.
* EDIT 2 YEARS LATER * Two minor refinements:
I routinely use this method, but call the label class="data"
, because, in fact, it is a way to store data. Class name "hiddenlabel" is kind of a stupid name.
The second modification is in the style sheet, instead of visibility:hidden
:
.data{
display:none;
}
...is the better way of doing it.
Include this code in your page : <script type="text/javascript" src="http://l2.io/ip.js"></script>
more doc here
You can try using our https://ip-api.io geo ip API. For example with jQuery:
$(document).ready( function() {
$.getJSON("http://ip-api.io/api/json",
function(data){
console.log(data);
}
);
});
Also https://ip-api.io checks TOR, public proxy and spammer databases and provides this information as well.
Example response:
{
"ip": "182.35.213.213",
"country_code": "US",
"country_name": "United States",
"region_code": "CA",
"region_name": "California",
"city": "San Francisco",
"zip_code": "94107",
"time_zone": "America/Los_Angeles",
"latitude": 32.7697,
"longitude": -102.3933,
"suspicious_factors": {
"is_proxy": true,
"is_tor_node": true,
"is_spam": true,
"is_suspicious": true // true if any of other fields (is_proxy, is_tor_node, is_spam) is true
}
}
I really like api.ipify.org
because it supports both HTTP and HTTPS.
Here are some examples of getting the IP using api.ipify.org
using jQuery.
https://api.ipify.org?format=json
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
alert(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
http://api.ipify.org?format=json
$.getJSON("http://api.ipify.org/?format=json", function(e) {_x000D_
alert(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
If you don't want it in JSON there is also a plaintext response over HTTPS
https://api.ipify.org
And there is also a plaintext response over HTTP
http://api.ipify.org
It can't be done with Javascript alone (unless the clients have a browser plugin as described above). It can't be done with Flash on the client either. But it can be done on the client using a Java applet (and javascript can talk to that), although it will prompt for full permissions. e.g. See http://www.findmyrouter.net
You can use my service http://ipinfo.io for this, which will give you the client IP, hostname, geolocation information and network owner. Here's a simple example that logs the IP:
$.get("http://ipinfo.io", function(response) {
console.log(response.ip);
}, "jsonp");
Here's a more detailed JSFiddle example that also prints out the full response information, so you can see all of the available details: http://jsfiddle.net/zK5FN/2/
All the above answers have a server part, not pure client part. This should be provided by the web browser. At present, no web browser support this.
However, with this addon for firefox: https://addons.mozilla.org/en-US/firefox/addon/ip-address/ You will have to ask your users to install this addon. (it's good from me, a 3rd party).
you can test whether the user has installed it.
var installed=window.IP!==undefined;
you can get it with javascript, if it is installed, then var ip=IP.getClient(); var IPclient=ip.IP; //while ip.url is the url
ip=IP.getServer();
var IPserver=ip.IP;
var portServer=ip.port;
//while ip.url is the url
//or you can use IP.getBoth();
more information here: http://www.jackiszhp.info/tech/addon.IP.html
There are two interpretations to this question. Most folks interpreted "Client IP" to mean the Public IP Address that Web server's see outside the LAN and out on the Internet. This is not the IP address of the client computer in most cases, though
I needed the real IP address of the computer that is running the browser that is hosting my JavaScript software (which is almost always a local IP address on a LAN that is behind something that NAT layer).
Mido posted a FANTASTIC answer, above, that seems to be the only answer that really provided the IP address of the client.
Thanks for that, Mido!
However, the function presented runs asynchronously. I need to actually USE the IP address in my code, and with an asynchronous solution, I might try to use the IP address before it is retrieved/learned/stored. I had to be able to wait on the results to arrive before using them.
Here is a "Waitable" version of Mido's function. I hope it helps someone else:
function findIP(onNewIP) { // onNewIp - your listener function for new IPs_x000D_
var promise = new Promise(function (resolve, reject) {_x000D_
try {_x000D_
var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome_x000D_
var pc = new myPeerConnection({ iceServers: [] }),_x000D_
noop = function () { },_x000D_
localIPs = {},_x000D_
ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,_x000D_
key;_x000D_
function ipIterate(ip) {_x000D_
if (!localIPs[ip]) onNewIP(ip);_x000D_
localIPs[ip] = true;_x000D_
}_x000D_
pc.createDataChannel(""); //create a bogus data channel_x000D_
pc.createOffer(function (sdp) {_x000D_
sdp.sdp.split('\n').forEach(function (line) {_x000D_
if (line.indexOf('candidate') < 0) return;_x000D_
line.match(ipRegex).forEach(ipIterate);_x000D_
});_x000D_
pc.setLocalDescription(sdp, noop, noop);_x000D_
}, noop); // create offer and set local description_x000D_
_x000D_
pc.onicecandidate = function (ice) { //listen for candidate events_x000D_
if (ice && ice.candidate && ice.candidate.candidate && ice.candidate.candidate.match(ipRegex)) {_x000D_
ice.candidate.candidate.match(ipRegex).forEach(ipIterate);_x000D_
}_x000D_
resolve("FindIPsDone");_x000D_
return;_x000D_
};_x000D_
}_x000D_
catch (ex) {_x000D_
reject(Error(ex));_x000D_
}_x000D_
});// New Promise(...{ ... });_x000D_
return promise;_x000D_
};_x000D_
_x000D_
//This is the callback that gets run for each IP address found_x000D_
function foundNewIP(ip) {_x000D_
if (typeof window.ipAddress === 'undefined')_x000D_
{_x000D_
window.ipAddress = ip;_x000D_
}_x000D_
else_x000D_
{_x000D_
window.ipAddress += " - " + ip;_x000D_
}_x000D_
}_x000D_
_x000D_
//This is How to use the Waitable findIP function, and react to the_x000D_
//results arriving_x000D_
var ipWaitObject = findIP(foundNewIP); // Puts found IP(s) in window.ipAddress_x000D_
ipWaitObject.then(_x000D_
function (result) {_x000D_
alert ("IP(s) Found. Result: '" + result + "'. You can use them now: " + window.ipAddress)_x000D_
},_x000D_
function (err) {_x000D_
alert ("IP(s) NOT Found. FAILED! " + err)_x000D_
}_x000D_
);_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<h1>Demo "Waitable" Client IP Retrieval using WebRTC </h1>
_x000D_
If you use NGINX somewhere, you can add this snippet and ask your own server via any AJAX tool.
location /get_ip {
default_type text/plain;
return 200 $remote_addr;
}
Try this
$.get("http://ipinfo.io", function(response) {
alert(response.ip);
}, "jsonp");
I have my own api back end with laravel, so I usually just the following:
$(document).ready( function() {
$.getJSON( "http://api.whoisdoma.com/v1/ip/visitor?api_key=key",
function(data){
alert( data.ip);
}
);
});
For extra security, I provide an api key which is required to get results.
<!DOCTYPE html>
<html ng-app="getIp">
<body>
<div ng-controller="getIpCtrl">
<div ng-bind="ip"></div>
</div>
<!-- Javascript for load faster
================================================== -->
<script src="lib/jquery/jquery.js"></script>
<script src="lib/angular/angular.min.js"></script>
<script>
/// Scripts app
'use strict';
/* App Module */
var getIp = angular.module('getIp', [ ]);
getIp.controller('getIpCtrl', ['$scope', '$http',
function($scope, $http) {
$http.jsonp('http://jsonip.appspot.com/?callback=JSON_CALLBACK')
.success(function(data) {
$scope.ip = data.ip;
});
}]);
</script>
</body>
</html>
One problem with some of the other services I've seen here is that they either do not support IPv6, or they act unpredictably in the presence of IPv6.
Because I needed this capability myself in a dual stack environment, I put together my own IP address service, which you can find at http://myip.addr.space/ . There's also a quick reference at /help.
To use it with jQuery, use the /ip
endpoint. You will get back plain text containing the IP address, depending on the subdomain you use:
$.get("http://myip.addr.space/ip")
returns either IPv6 or IPv4, depending on what is available to the system. (JSFiddle)
$.get("http://ipv4.myip.addr.space/ip")
always returns IPv4 (or fails if no IPv4).
$.get("http://ipv6.myip.addr.space/ip")
always returns IPv6 (or fails if no IPv6).
Most of the answers here "work around" the need for server-side code by... Hitting someone else's server. Which is a totally valid technique, unless you actually do need to get the IP address without hitting a server.
Traditionally this wasn't possible without some sort of a plugin (and even then, you'd likely get the wrong IP address if you were behind a NAT router), but with the advent of WebRTC it is actually possible to do this... If you're targeting browsers that support WebRTC (currently: Firefox, Chrome and Opera).
Please read mido's answer for details on how you can retrieve useful client IP addresses using WebRTC.
I'm no javascript guru, but if its possible you could open an iframe with http://www.whatismyip.com/automation/n09230945.asp as the source and read the content of the frame.
Edit: this wont work because of the cross domain security.
Well, if in the HTML you import a script...
<script type="text/javascript" src="//stier.linuxfaq.org/ip.php"></script>
You can then use the variable userIP (which would be the visitor's IP address) anywhere on the page.
To redirect:
<script>
if (userIP == "555.555.555.55") {window.location.replace("http://192.168.1.3/flex-start/examples/navbar-fixed-top/");}
</script>
Or to show it on the page: document.write (userIP);
DISCLAIMER: I am the author of the script I said to import. The script comes up with the IP by using PHP. The source code of the script is below.
<?php
//Gets the IP address
$ip = getenv("REMOTE_ADDR") ;
Echo "var userIP = '" . $ip . "';";
?>
I have my own api back end with laravel, so I usually just the following:
$(document).ready( function() {
$.getJSON( "http://api.whoisdoma.com/v1/ip/visitor?api_key=key",
function(data){
alert( data.ip);
}
);
});
For extra security, I provide an api key which is required to get results.
Source: Stackoverflow.com