1<?php
2/*
3 * Copyright (c) 2002-2006 Martin Jansen
4 *
5 * Permission is hereby granted, free of charge, to any person obtaining
6 * a copy of this software and associated documentation files (the
7 * "Software"), to deal in the Software without restriction, including
8 * without limitation the rights to use, copy, modify, merge, publish,
9 * distribute, sublicense, and/or sell copies of the Software, and to
10 * permit persons to whom the Software is furnished to do so, subject to
11 * the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *
24 * $Id: CheckIP.php 304730 2010-10-25 08:51:32Z clockwerx $
25 */
26
27/**
28* Class to validate the syntax of IPv4 adresses
29*
30* Usage:
31*   <?php
32*   require_once "Net/CheckIP.php";
33*
34*   if (Net_CheckIP::check_ip("your_ip_goes_here")) {
35*       // Syntax of the IP is ok
36*   }
37*   ?>
38*
39* @author  Martin Jansen <mj@php.net>
40* @author  Guido Haeger <gh-lists@ecora.de>
41* @package Net_CheckIP
42* @version 1.1
43* @access  public
44*/
45class Net_CheckIP
46{
47
48    /**
49    * Validate the syntax of the given IP adress
50    *
51    * This function splits the IP address in 4 pieces
52    * (separated by ".") and checks for each piece
53    * if it's an integer value between 0 and 255.
54    * If all 4 parameters pass this test, the function
55    * returns true.
56    *
57    * @param  string $ip IP adress
58    * @return bool       true if syntax is valid, otherwise false
59    */
60    function check_ip($ip)
61    {
62        $oct = explode('.', $ip);
63        if (count($oct) != 4) {
64            return false;
65        }
66
67        for ($i = 0; $i < 4; $i++) {
68            if (!preg_match("/^[0-9]+$/", $oct[$i])) {
69                return false;
70            }
71
72            if ($oct[$i] < 0 || $oct[$i] > 255) {
73                return false;
74            }
75        }
76
77        return true;
78    }
79}
80?>
81