Jump to content

[SOLVED] Verify IP address is valid.


lynxus

Recommended Posts

Hi guys, Im trying to figure out how to verify a IP address is valid but failing lol. Mainly because im new to PHP.

 

So any help would be oh so helpfull!

 

My script normally contains quite a lot of  IP address's so what would be handy is if one of my vars had a invalid IP it would make my global var of $error = "1" and maybe echo what $var had the bad ip in.

 

So in this instance i would have something like..

 

$ip1 = _$POST['$ip1'];

$ip2 = _$POST['$ip2'];

$ip3 = _$POST['$ip3'];

 

lets say ip1 had "10.0.0.0" that would be valid ( 4 octets full and below 256 )

if it had "10.0.0"  that would be invalid. not 4 octects

if it had "10.0.0.300" that would be invalid.. 4 octect but over 255 ..

 

Does this make any sense?

 

How would i go about validating these vars and then changing my global $error var to 1 if they fail the check?

 

I suppose a function?

 

function checkip($ip){

if $ip = invalid then return "1";

}

 

$error = checkip($ip1);

 

Im guess i sorta see what i need to do? but reallly need help on actually doing it?

 

Many Thanks

Graham

 

Link to comment
Share on other sites

Well, the function would probably look something like:

 

<?php
function verify_ip($ip){
    $parts = explode('.',$ip);
    if(count($parts) < 4){
        return FALSE;
    }
    foreach($parts as $v){
        if(!ctype_digit($parts) || $parts > 255){
            return FALSE;
        }
    }
    return TRUE;
}
?>

Link to comment
Share on other sites

I would shorten it up with regex and do a lookup:

 

<?php
function verify_ip($ip){
  if(preg_match('/^(\d{1,3}\.){3}\d{1,3}$/',$ip)) //Make sure it's ###.###.###.###
    return checkdnsrr($ip); //Check DNS
  return false;
}
?>

Link to comment
Share on other sites

I would shorten it up with regex and do a lookup:

 

<?php
function verify_ip($ip){
  if(preg_match('/^(\d{1,3}\.){3}\d{1,3}$/',$ip)) //Make sure it's ###.###.###.###
    return checkdnsrr($ip); //Check DNS
  return false;
}
?>

 

Hi thanks ( both of you )

I will give them a try and see what happens :) Thanks

-g

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.