PHP :: Determine the A, B or C Class Network of an IP Address

By | 21/03/2014

I use the code below to determine the A, B or C class of an IP address. This was helpful for identifying a student on our internal network so that they access the Intranet without needing to log in.

<?php
    function ipClass($ip) {
        try {
            $array = explode(".", $ip);
            $a = $array[0] . ".0.0.0";
            $b = $array[0] . "." . $array[1] . ".0.0";
            $c = $array[0] . "." . $array[1] . "." . $array[2] . ".0";
            $d = $array[0] . "." . $array[1] . "." . $array[2] . "." . $array[3];
            $network = array ('A' => $a, 'B' => $b, 'C' => $c, 'HOST' => $d);
            return ($network);
        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
        }
    }

    function Secure($ip) {
        try {
            // Check if in a 'A' Class Range
            $network = ipClass($ip);

            // Check if in a 'A' Class Range
            $ipRange = array('127.0.0.0');
            if (in_array ($network['A'], $ipRange)) {
                return (TRUE);
            } 

            // Check if in a 'B' Class Range
            $ipRange = array('10.7.0.0', '10.8.0.0', '10.16.0.0');
            if (in_array ($network['B'], $ipRange)) {
                return (TRUE);
            } 

            // Check if in a 'C' Class Range
            $ipRange = array('192.168.0.0');
            if (in_array ($network['C'], $ipRange)) {
                return (TRUE);
            } 

            // Check Individual Hosts
            $ipRange = array('192.168.0.7', '192.168.0.13');
            if (in_array ($network['HOST'], $ipRange)) {
                return (TRUE);
            } 

            return (FALSE); // Security on
        } catch (PDOException $e) {
            print "Error!: " . $e->getMessage() . "<br/>";
            die();
        }
    }
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.