How to get local IP address using JavaScript? [duplicate]

I want to get local IP address of a client system. How can I achieve this using JavaScript ?

Answers:

Answer

I don't think you can without some server interaction.

The easiest way would be making an AJAX request to a server-side snippet that, in PHP, would look like this:

<?php echo $_SERVER["REMOTE_ADDR"]; ?>
Answer

You can't directly. One approach could be to send an AJAX request to your server (if there is one), which can return the IP address from which the user is viewing the current page.

Answer

you probably need an external party that will tell you; even if it were possible to get the local ip from javascript (which I doubt) you will most of the time get private ip address in ranges 10.x.x.x or 192.168.x.x (or that other one which I just can't seem to remember)

So put the ip in the page by php, like suggested above, of have a dedicated script echoing just the remote ip. That will then be the ip you have as seen from on the internet.

Answer

I think, you can't. But if your server has at least Server Side includes (SSI) - which every apache installation has enabled by default - you can get the ip like this:

var ip = '<!--#echo var="REMOTE_ADDR"-->';
Answer

This works on my Mac when embedded in NodeJS code, and gives the local IP address of the server running the code:

// get local IP address - Command line used is:  ipconfig getifaddr en0
  const { spawnSync } = require( 'child_process' );
  const ip = spawnSync(  'ipconfig', [ 'getifaddr', 'en0' ] );
// the two outputs generated:
  console.log( `stderr: ${ip.stderr.toString()}` );
  console.log( `stdout: ${ip.stdout.toString()}` );
// applied:
  console.log( 'This JavaScript is running on: ' + ip.stdout.toString() );

Note: 'en0' is the network interface in this case - you may find that your network connection is through 'en1' or 'en2' etc, so you will need to add a bit of logic to find which interface is being used.

Hope this helps

Phil

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.