Thread: Valid IP in php

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 1999
    Location
    Santo Domingo, DN, Dominican Republic
    Posts
    1
    Rep Power
    0
    I've been trying to determine if a string coming from an html form is a valid IP address, I tried using the regexp's functions, but I can't hit the clown yet, so I'm asking you out if you can give me a hand on here.

    I've split the string on 4 strings more separated by ".", then determine if each of those is a number, but... what if the user enters just letters??

    Some help would be appreceiated...

    ------------------
    Bigotes :{
  2. #2
  3. No Profile Picture
    Apprentice Deity
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Jul 1999
    Location
    Niagara Falls (On the wrong side of the gorge)
    Posts
    3,237
    Rep Power
    19
    A regex solution might be an idea but I'd hate to tackle it since the range is not easy to deal with. I see this as four steps:

    1) break up the elements
    2) verify number of elements=4
    3) verify all integers
    4) verify valid range

    to wit:
    $invalid=0;
    $levels=explode('.',$ip);
    if (count($levels)!=4) $invalid='true';
    for ($i=0;$i<4;$i++)
    {
    if ($levels[$i]!=intval($levels[$i]) $invalid='true';
    if ($levels[$i]<0 OR $levels[$i]>256) $invalid='true';
    }

    if ($invalid)
    {
    // $ip not a valid ip address
    }else
    {
    // $ip valid
    }

    Technically some values of $ip would not be valid that would slip thru, but this should be good enough for most applications.

    HTH

    Rod
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2000
    Location
    Oslo, Norway
    Posts
    5
    Rep Power
    0
    I use:

    <BLOCKQUOTE><font size="1" face="Verdana,Arial,Helvetica">code:</font><HR><pre>
    if (ereg("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}",$ip)) {
    print "The IP is valid.";
    }
    else {
    print("The IP is not valid.");
    }
    [/code]

    If you want to check everything you could make sure its not part of the 10.* A class or the 192.168.* B class since those are reserved for private networks.

    N.

Similar Threads

  1. Replies: 2
    Last Post: August 18th, 2004, 10:45 PM
  2. Replies: 4
    Last Post: January 28th, 2004, 08:29 AM
  3. PHP with UnixODBC
    By coder4hire in forum PHP Development
    Replies: 2
    Last Post: January 20th, 2004, 01:14 PM
  4. Passing string from PHP to Javascript
    By ka8oad in forum JavaScript Development
    Replies: 4
    Last Post: January 17th, 2004, 03:12 PM
  5. UnixODBC + PHP + Apache + Empress
    By coder4hire in forum Database Management
    Replies: 0
    Last Post: January 15th, 2004, 01:41 PM

IMN logo majestic logo threadwatch logo seochat tools logo