This question already has answers here:
Can You Get A Users Local LAN IP Address Via JavaScript?
(9 answers)
Closed 3 years ago.
I want to get local IP address of a client system. How can I achieve this using JavaScript ?
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"]; ?>
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.
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.
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"-->';
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
Related
I'm building a react app and want to allow/deny access to some components based (mainly filter IP||MAC) on where the client is.
Any way to restrict routing to deny access to a presentation when the client is connecting from the internet allowing the access when it connects via LAN?
I think I found an alternative approach, I will maintain the question open looking for alternatives.
I read that the client should not be able to see its ip address (browser security), and that should be done on the server side (thats a direct approach as mentioned in the above post) (can anyone confirm that).
The solution is to find the gateway address of the client (normally using NAT) and compare with my gateway address, if equal they are inside LAN.
I am having a situation that on the computer I am able to see the ip address, on mobile/cellphone I can't, need to investigate.
import React from 'react';
export default () => {
const [addrObj, setAddrObj] = React.useState({});
const fetchAddrData = async () =>
await fetch('http://jsonip.com')
.then(res => res.json())
.then(setAddrObj);
React.useEffect(() => {fetchAddrData()},[])
return (
<>
<h3>Sample Page</h3>
<h4>addr: {addrObj.ip}</h4>
</>
)
}
From what I've just read, JS alone can't retrieve the IP address. You might want to store it to a JS variable in the <head> with PHP, like
<?php echo '<script>var ip = '.$_SERVER['REMOTE_ADDR'].'</script>' ?>
This way the IP address is available to your JS.
And this post can help you track the location, even though you might want to use PHP for that as well.
How to get client's IP address using JavaScript?
And if you really don't want to use PHP, than this article uses jQuery. It does a request though. I'm not sure how important performance is to you.
https://www.geeksforgeeks.org/how-to-get-client-ip-address-using-javascript/
How to get client's IP address using JavaScript?
How can I make an HTML (and CSS/PHP/JavaScript) document which only allows certain IP addresses on a page?
(I am not asking how to find IP address with PHP, but how to allow access to a page based on an IP address.)
put this on the top of your php file and update the allowedIps variable with the IPs that you want to allow.
$allowedIps = ['198.x.x.x', '200.x.x.x'];
$userIp = $_SERVER['REMOTE_ADDR'];
if (!in_array($userIp, $allowedIps)) {
exit('Unauthorized');
}
for non PHP files (eg .html, .css) you will have to update your .htaccess file to add file specific permission. The following SOF thread should help: (assuming you are using apache server)
.htaccess: how to restrict access to a single file by IP?
If you dont want to bother with the code, put your site on Cloudflare and block ips
Try this with PHP :
function CheckIPAccess() {
//allowed IP. Change it to the IP addresses you want to allow to access your webpage
$allowedip = '127.0.0.1';
$ip = $_SERVER['REMOTE_ADDR'];
return ($ip == $allowedip);
}
Usually, IP restrictions are done at the web-server configuration level, so that unauthorized IPs simply can't reach your code at all.
It would actually be quite messy to try to do this kind of check within your application – "you'd undoubtedly miss one" – but the server can easily do it for you.
(I do not recommend attempting to use IPs for privilege checking and so forth ... "IPs change. Frequently. Very messy. Very ...")
Even stronger yet would be firewalls, and maybe VPNs. You really want to keep intruders as far away as possible and to give them as little information as possible. (For instance, why should they even be able to detect that the web-server exists?) Strive to make the entire setup as "hardened" as possible.
I need to get the machine name and ip using php/javacript - when I run the webpage on the localhost I am getting the correct computer name and ip address but when I put the page on the webserver and run the same online - the code is returning the ip address of the client machine only NOT the name of machine-name.
I somehow need to get the client machine name and save it in the database for later operation.
So I tried in three ways:
Method 1 (php):
gethostbyaddr($_SERVER['REMOTE_ADDR']); -- return the ip
getenv('COMPUTERNAME'); -- return the ip only
Method 2(php):
echo shell_exec('echo %computername%'); -- return none instead of client computer name
Method 3 (javascript):
alert(window.location.hostname);
None of them are not working.
I'm seeking your assistance.
Thank you.
The environment on the server is clearly different to your local machine.
Try var dumping the SERVER global to see what info you do have access to:
var_dump($_SERVER);
I've setup a physical mac computer to be a MySQL server. It works perfectly well if I access it remotely on the internet if I access it through the Terminal. Edit: I now realise this is on the local network only. So I'm now setting up a static IP and will have to post another question on that if I get stuck
But I'd love to solve why it someone doesn't work if I connect with javascript, such as in GoogleSpreadsheets or any related add-ons in GoogleSpreadsheets (which are also written on Javascript I think).
I can use any of those javascript approaches to connect to other databases which I have access to, but I'd like to find out why I can't connect to mine in particular and if there is anything I can change? Thanks.
I setup a MySQL server on computer A (Mac OS X Yosemite). I can connect fine if I use do the following in bash on computer B (Mac OS El Capitan) and then get whatever output I need from MySQL.
$ # in bash, change path to ensure SQL runs
$ export PATH=$PATH:/usr/local/mysql/bin/
$ # start sql and run a query
$ mysql -u test -pXXXXX -h 192.168.XXX.XX sakila # replace X's with real credentials, where -p is for the password and -h is for the IP address.
$ mysql> SHOW TABLES;
$ mysql> #... output is good
$ mysql> exit;
$
If I run the same credentials in Google Spreadsheets script editor, I get an error on the last line saying that either my connection string, user or password are not correct. See script below.
// attempt to access SQL data using javascript on https://script.google.com
function Drive() {
var ServerIP = '192.168.XXX.XX'; // IP address of the server. replace with real IP
var SQL_Port = '3306'; // port number
var SQL_Usr = 'test'; // name of user
var SQL_Pwd = 'xxxxx'; // password of user. replace with real password
var SQL_DB = 'sakila'; // name of sample database downloaded from MySQL Workbench documentation.
var connectorInstance = 'jdbc:mysql://' + ServerIP +':' + SQL_Port;
var ConnectString = connectorInstance + '/' + SQL_DB;
var conn = Jdbc.getConnection(ConnectString, SQL_Usr, SQL_Pwd); // error on this line
}
My javascript, my syntax is definitely correct, since if I swop in the credentials for another online database then the error disappears. Similarly, I tried 4 different Google Spreadsheets add-ons which are available when you search "SQL" in the add-on store; those work with all databases I tried but not my own.
And my own server's credentials and authorisation should be working correctly, since I can connect using bash as shown at the top.
Is there some security option setup on the other databases in the server or in their internet connection which means javascript will connect on theirs and not mine? Is there something I missed?
My alternatives would be to only access the server with bash (not good when I am building a Spreadsheet-based front-end), or to host the server online, which would involve some costs.
Would an SSH connection help at all? I haven't used one before. Any help would be appreciated.
Steps I've tried
I started off setting up MySQL Workbench with a config file as -"etc/my.cnf".
I set "skip-networking" off.
I made sure "bind_address" was off and also tried variations since as "0.0.0.0", "*" and "%".
I followed a lesson on setting up javascript code for Google scripts and granted sufficent user account details on location "%" (yes I know that's not secure but this is a small test db).
I've tried playing around with other Options File preferences under Networking or other section, but they either have no effect or the server fails to restart successfully with those applied.
Before testing my DB connection, I make sure I restart my SQL server to ensure option and user changes are applied.
I've checked StackOverflow to see who else is asking about remote databases, javascript or connection strings. No one else seems to have my exact issue.
I've tried using the host's name "Servers-Macbook-Air.local" in place of IP, again that works in bash but NOT in Javascript still. Also if I use IP or hostname for another database, that works.
I did some research after Hardy's comment - I think it is the private IP restricting me. I had only tried with both laptops in Wifi range.
http://www.gohacking.com/private-and-public-ip-addresses/
Say for example, if a network X consists of 10 computers, each of them can be given an IP starting from 192.168.1.1 to 192.168.1.10. Unlike the public IP, the administrator of the private network is free to assign an IP address of his own choice (provided the IP number falls in the private IP address range as mentioned above).
Devices with private IP addresses cannot connect directly to the Internet. Likewise, computers outside the local network cannot connect directly to a device with a private IP.
Your problem is you are trying to your local IP address of 192.168.xxx.xxx
You can not do that from the internet. As a matter of fact, that IP address only exists within your network. You and I could both have the IP of 192.168.1.10. Most off-the-shelf routers create networks that begin with 192.168.1.1 (which is probably where you can access your firewall).
The only way this could work is if you used your public IP address and you have the port you are looking for configured to point to your machine. This would typically require some Port Forwarding or Firewall configuration.
You can check your public IP with sites like http://www.ipchicken.com
I'm trying to find a resource to get a few things about the user identity for security purposes. I'm trying to get ipv6 ipaddress, and the computer name or host name using classic asp and vb6. If I can't use vb6 I would like to use jQuery or javascript if possible.
In asp, I can get the ipv4 using request.ServerObject("REMOTE_ADDR") I believe.
If you need this in ASP I'm unaware of anything you can use to get this directly.
It is possible to write a Class in VB6 that calls DnsQuery in Dnsapi.dll to do first a DNS_TYPE_PTR query to reverse-lookup the IPv4 address to get the DNS name and then a DNS_TYPE_AAAA query to retrieve the corresponding IPv6 address (if any).
...
Hmm, no code handout no rep eh? (insert smiley here)
Well this is a bit of code to post here inline... maybe look at {VB6} DNS Lookup Class as a starting point.
Not sure if this is what you're after, but there is some information here about building a GUI in VB to track an IP address:
http://www.youtube.com/watch?v=hkDD03yeLnU