Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an IP address is private

Tags:

php

private

ip

I like to check if an IP address is in a private network. It doesn't work.

My code:

<?php $ip = $_SERVER['REMOTE_ADDR'];  function _isPrivate($ip)  {     $i = explode('.', $ip);      if ($i[0] == 10) {         return true;     } else if ($i[0] == 172 && $i[1] > 15 && $i[1] < 32) {         return true;     } else if ($i[0] == 192 && $i[1] == 168) {         return true;     }     return false; } ?> 

The other one:

<?php $ip = $_SERVER['REMOTE_ADDR'];  function _isPrivate($ip)  {     $ip = ip2long($ip);     $net_a = ip2long('10.255.255.255') >> 24;      $net_b = ip2long('172.31.255.255') >> 20;      $net_c = ip2long('192.168.255.255') >> 16;       return $ip >> 24 === $net_a || $ip >> 20 === $net_b || $ip >> 16 === $net_c;  } ?> 

Any help would be much appreciated, thanks!

like image 490
Ruth Avatar asked Dec 11 '12 10:12

Ruth


People also ask

Is 192.168 private or public?

And don't be surprised if you have a device or two at home with a so-called 192 IP address, or a private IP address beginning with 192.168. This is the most common default private IP address format assigned to network routers around the globe.

Can you look up a private IP address?

Windows. Search for cmd in the Windows search bar, then in the command line prompt, type ipconfig to view the private IP address. Mac. Select system preferences, then click on network to view the private IP address.

What IP address is private?

The Internet Assigned Numbers Authority (IANA) reserves the following IP address blocks for use as private IP addresses: 10.0. 0.0 to 10.255. 255.255.


1 Answers

I think this should solve the problem.

filter_var used with the following validation rules will return false if the IP address is a private one.

$user_ip = '127.0.0.1'; filter_var(     $user_ip,      FILTER_VALIDATE_IP,      FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE |  FILTER_FLAG_NO_RES_RANGE ) 

Check the links above for the php documentation

like image 99
Dmitri Pavlutin Avatar answered Oct 16 '22 23:10

Dmitri Pavlutin