tags:

views:

518

answers:

3

Hi there,

I want to check via php if someone connects to my site via IPv4 or IPv6.

The client address can be found in $_SERVER["REMOTE_ADDR"] but how to check if it's IPv4 or IPv6 ?

Thank you for your time

Andre

+3  A: 

What about counting the number of '.' and/or ':' in $_SERVER["REMOTE_ADDR"] ?

If there is more than 0 ':', and no '.' symbol in $_SERVER["REMOTE_ADDR"], I suppose you can consider you user is connected via IPv6.


Another solution might be to use the filter extension : there are constants (see the end of the page) that seem to be related to IPv4 and IPv6 :

FILTER_FLAG_IPV4 (integer)
Allow only IPv4 address in "validate_ip" filter.

FILTER_FLAG_IPV6 (integer)
Allow only IPv6 address in "validate_ip" filter.

Pascal MARTIN
Don't assume that if there are '.' it's an IPv4, IPv6 can also contain IPv4-style addresses eg: 0:0:0:0:0:127.0.0.1
Christian Sciberras
+2  A: 

IPv4 addresses all match the regex /^\d{1,3}(\.\d{1,3}){3,3}$/.

Justice
looks that it does the job. but hey .... it's regular expression! it can do everything, if you just know how...
+2  A: 

You can use this:

function ipVersion($txt) {
     return strpos($txt, ":") === false ? 4 : 6;
}
Cem Kalyoncu
Like this better than regexp - it's faster :)
bisko
yes ... seems to be faster