tags:

views:

122

answers:

3

I'm making a script, in which the user needs to enter a valid IP address. How can I check that it's a valid IP address? (Doesn't need to resolve)

Basically $_POST['ip'] just needs to be between 0.0.0.0 and 255.255.255.255

A: 
  1. Split your "IP" string by "."
  2. Verify that there are four entries (octet) in the array.
  3. Verify: 0 <= octet <= 255
  4. If you want to get fancier, you can check that the IP isn't in a private network, isn't a multicast network, or isn't in the reserved space.

Edit: Use the built in PHP method if available! :)

Yann Ramin
What do you mean about 4?
Rob
I think you meant: 0 ≤ octet ≤ 255.
Gumbo
+8  A: 

If you're running PHP >= 5.2, use the Filter extension:

filter_var($ip, FILTER_VALIDATE_IP)

More info here and here.

deceze
Sorry, didn't see this until after I posted mine.
El Yobo
Wow, that's incredibly convenient. Thanks!
Rob
+1  A: 

You could also try preg_match(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/, $_POST['ip']).

More about preg_match() here

Also there are many patterns for validation. Choose most suitable one for you.


Update: Also about using filters. Not all servers have already PHP equal or higher, than 5.2.0. So u can check version before using them, but IMHO most logical ways would be Filters or PCRE.

Eugene