ilnur777
ilnur777

Reputation: 1145

PHP: detecting IP's entry to a specific IP range

I have the PHP function that determines whether one IP goes to a specific IP range, but I don't know how to find out the IP's network and mask. Can anyone help with this?

<?
// Example of calling and checking IP-address 192.168.0.4
// belonging to a network 192.168.0.0 with mask 255.255.255.248

if(ip_vs_net("192.168.0.4","192.168.0.0","255.255.255.248")){
print "Address belongs to a netwok<BR>";
} else {
print "Address is out of subnetwork's range<BR>";
}

function ip_vs_net($ip,$network,$mask){
if(((ip2long($ip))&(ip2long($mask)))==ip2long($network)){
return 1;
} else {
return 0;
}
}
?>

Upvotes: 1

Views: 4462

Answers (3)

ZZ Coder
ZZ Coder

Reputation: 75496

When the IP address was classy (Class A, B, C etc), it was easy to find the subnet mask because it's fixed depending on the address ranges.

Now with CIDR, it's impossible to know the exact subnet mask because any contiguous prefix can be used as subnet mask.

However, the classy subnet might work for your case. It's definitely better than nothing. You can figure out the subnet mask using this function,

function get_net_mask($ip) {
   if (is_string($ip)) {
      $ip = ip2long($ip);
   }
   if (($ip & 0x80000000) == 0) {
       $mask = 0xFF000000;
   } elseif (($ip & 0xC0000000) == (int)0x80000000) {
       $mask = 0xFFFF0000;
   } elseif (($ip & 0xE0000000) == (int)0xC0000000) {
       $mask = 0xFFFFFF00;
   } else {
       $mask = 0xFFFFFFFF;
   }
   return $mask;
}

Upvotes: 1

Zak
Zak

Reputation: 25237

Kind of, but not really. You should never really care or have to care about external network netmasks or network.

However, if you are internal to a network, and a DHCP server is available, you can query it via the DHCP protocol to get your internal (local) network settings. If you are in a LAN, you may also be able to use something like the RIP protocol to communicate with the network devices. I'm guessing however you are more interested in some kind of port scanning using nmap or something and aren't really that interested in networking... In which case .. FUH :)

Upvotes: 1

Mitch Dempsey
Mitch Dempsey

Reputation: 39939

You can't just find out the mask based on the IP. You need to know what the subnet is or something, the same IP could exist in 32ish subnets.

Upvotes: 2

Related Questions