tags:

views:

241

answers:

3

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;
}
}
?>
+2  A: 

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.

webdestroya
+1  A: 

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 :)

Zak
Zak, it's really hard to understand what you've said! :-) I just want to use it on my website and want to allow using only 1 subnetwork for definite user!
ilnur777
You say that, but your example shows using a 192.x.x.x address which is by definition an internal (non-Internet) network address. Are you instead saying you want to find out if someone is coming from the same external source on the internet ?If so, I would say just run a traceroute to their IP and record what the last hop router IP address is. Use that as their authentication rather than a network subnet.
Zak
+1  A: 

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;
}
ZZ Coder