Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check whether the given IP is internal or not

Tags:

javascript

How do you check whether a given IP is internal or not using only javascript?

For example if you are given an IP of 192.168.1.1 the script should validate this and alert if this is an internal or external IP.

like image 357
Sreehari Avatar asked Nov 28 '22 16:11

Sreehari


1 Answers

If you mean private just make sure it's in one of the following ranges:

Private IP address ranges

The ranges and the amount of usable IP's are as follows:

10.0.0.0 - 10.255.255.255 Addresses: 16,777,216

172.16.0.0 - 172.31.255.255 Addresses: 1,048,576

192.168.0.0 - 192.168.255.255 Addresses: 65,536

Function like this should help:

function isPrivateIP(ip) {
   var parts = ip.split('.');
   return parts[0] === '10' || 
      (parts[0] === '172' && (parseInt(parts[1], 10) >= 16 && parseInt(parts[1], 10) <= 31)) || 
      (parts[0] === '192' && parts[1] === '168');
}
like image 102
Minko Gechev Avatar answered Jan 14 '23 16:01

Minko Gechev