Reputation: 1741
Is there any way you can find the IP of the server that the browser is connected to? For e.g. if the browser is accessing http://www.google.com, can we tell in any way what IP it is connected to? This is very useful in cases where Round-robin DNS is implemented. So say, the first request to a.com
results in 1.1.1.1
& subsequent request result in 1.1.1.2
& so on.
I couldn't find any way to do it with JavaScript. Is it even possible? If not is there any universal way to find this info out?
Upvotes: 40
Views: 180486
Reputation: 712
I am sure the following code will help you to get ip address.
<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>
Upvotes: -4
Reputation: 2469
Fairly certain this cannot be done. However you could use your preferred server-side language to print the server's IP to the client, and then use it however you like. For example, in PHP:
<script type="text/javascript">
var ip = "<?php echo $_SERVER['SERVER_ADDR']; ?>";
alert(ip);
</script>
This depends on your server's security setup though - some may block this.
Upvotes: 19
Reputation: 1763
Try this as a shortcut, not as a definitive solution (see comments):
<script type="text/javascript">
var ip = location.host;
alert(ip);
</script>
This solution cannot work in some scenarios but it can help for quick testing. Regards
Upvotes: 58
Reputation: 303
The one place that you can definitely get this answer is from the server's socket table, if you are the implementor of the server-side code that the client is connecting to. For example, in a Node.js Express app, it's available as req.socket.localAddress
. If that is going through address translation though, it probably isn't a useful answer for the client.
Although the client can only ever make educated guesses at what address it is connecting to, there is one piece of information that the client device definitely does have: the destination address of the TCP socket that the response is being delivered from. The browser application has access to this information from the OS, but I can't speak to whether it exposes it to the client application, or how.
Discussion
A TCP socket cannot be formed without a 4-tuple: Source & destination IP address and source & destination TCP port. There can only be one such active 4-tuple at any given time, and it uniquely identifies that TCP request between the two hosts. The sent packets have to go to the same address that the response packets come from (from the host's perspective), or the host will drop them rather than forward to the application.
With address translation and port mapping, the server socket may not share a single element of the tuple in common with the client socket, but within the host it has to be consistent.
Upvotes: 0
Reputation: 72
You could do a nslookup on location.hostname
!
Notes in the comments
Scroll down till One perfect snippet if you want something to copy paste without modifications.
Use DoHjs!
Add this to the HTML:
<script src="https://cdn.jsdelivr.net/npm/dohjs@latest/dist/doh.min.js"></script>
and then in JS:
const resolver = new doh.DohResolver('https://1.1.1.1/dns-query');
resolver.query(location.hostname, 'A')
.then(response => {
response.answers.forEach(ans => console.log(ans.data));
})
.catch(err => console.error(err));
See DoHjs for more information on how this works.
Use the enclout API:
const oReq = new XMLHttpRequest();
oReq.onload = function () {
const response = JSON.parse(this.responseText);
alert(JSON.stringify(response.dns_entries));
}
oReq.open("get", "https://www.enclout.com/api/v1/dns/show.json?auth_token=rN4oqCyJz9v2RRNnQqkx&url=" + encodeURIComponent(location.hostname), true);
oReq.send();
If you do not trust the snippet, how it works is described in the comments and earlier in this answer.
This is method 1 + comments
function getIP() {
return new Promise((resolve, reject) => {
const resolver = new doh.DohResolver("https://1.1.1.1/dns-query");
resolver
.query(location.hostname, "A")
.then((response) => {
response.answers.forEach((ans) => {
resolve(ans.data)
});
if (response.answers.length == 0) {
resolve(location.hostname)
}
})
.catch((err) => reject(err));
});
}
getIP().then((res) => {
document.getElementById("ip").innerText = res;
});
<script src="https://cdn.jsdelivr.net/npm/dohjs@latest/dist/doh.min.js"></script>
<p>The IP this is running on will be displayed below.</p>
<p id="ip"></p>
Upvotes: 4
Reputation: 349
I think you may use the callback from a JSONP request or maybe just the pure JSON data using an external service but based on the output of javascript location.host
that way:
$.getJSON( "//freegeoip.net/json/" + window.location.host + "?callback=?", function(data) {
console.warn('Fetching JSON data...');
// Log output to console
console.info(JSON.stringify(data, null, 2));
});
I'll use this code for my personal needs, as first I was coming on this site for the same reason.
You may use another external service instead the one I'm using for my needs. A very nice list exist and contains tests done here https://stackoverflow.com/a/35123097/5778582
Upvotes: 7
Reputation: 38859
Not sure how to get the IP address specifically, but the location object provides part of the answer.
e.g. these variables might be helpful:
self.location.host
- Sets or retrieves the hostname and port number of the locationself.location.hostname
- Sets or retrieves the host name part of
the location or URL.Upvotes: 14
Reputation: 299
I believe John's answer is correct. For instance, I'm using my laptop through a wifi service run by a conference centre -- I'm pretty sure that there is no way for javascript running within my browser to discover the IP address being used by the service provider. On the other hand, it may be possible to address a suitable external resource from javascript. You can write your own if your own by making an ajax call to a server which can take the IP address from the HTTP headers and return it, or try googling "find my ip". The cleanest solution is probably to capture the information before the page is served and insert it in the html returned to the user. See How to get a viewer's IP address with python? for info on how to capture the information if you are serving the page with python.
Upvotes: 1
Reputation: 4598
Can do this thru a plug-in like Java applet or Flash, then have the Javascript call a function in the applet or vice versa (OR have the JS call a function in Flash or other plugin ) and return the IP. This might not be the IP used by the browser for getting the page contents. Also if there are images, css, js -> browser could have made multiple connections. I think most browsers only use the first IP they get from the DNS call (that connected successfully, not sure what happens if one node goes down after few resources are got and still to get others - timers/ ajax that add html that refer to other resources).
If java applet would have to be signed, make a connection to the window.location (got from javascript, in case applet is generic and can be used on any page on any server) else just back to home server and use java.net.Address to get IP.
Upvotes: 2
Reputation: 1741
Actually there is no way to do this through JavaScript, unless you use some external source. Even then, it might not be 100% correct.
Upvotes: 2
Reputation: 81
You cannot get this in general. From Javascript, you can only get the HTTP header, which may or may not have an IP address (typically only has the host name). Part of the browser's program is to abstract the TCP/IP address away and only allow you to deal with a host name.
Upvotes: 6