20

Is it safe to assume that $_SERVER['REMOTE_ADDR'] always returns a IPv4 address?

Thanks!

Alix Axel
  • 151,645
  • 95
  • 393
  • 500

2 Answers2

26

The REMOTE_ADDR key is set by the web server, not PHP. If the web server listens on v6 and the user connects that way, it'll be a v6 address

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • +1, Thanks! I'm gonna try to figure out how I can convert an IPv6 address to a number. – Alix Axel Apr 12 '10 at 03:06
  • 3
    http://php.net/manual/en/function.inet-pton.php will convert v4 and v6 "string" addresses to their packed representation. – Marc B Apr 12 '10 at 21:54
  • @Michael IPv6 has many text representations. Is there a standard representation returned by `$_SERVER['REMOTE_ADDR']`? – Pacerier Jun 24 '12 at 14:27
  • @Pacerier You'll get the normal compacted IPv6 addresses or IPv4-mapped IPv6 addresses on a dual-stack system. – Michael Hampton Dec 03 '12 at 06:54
1

I have seen a bad IP address reported to php in REMOTE_ADDR from Apache 2.

It was '183.60..244.37'.

So the answer to your question, "Is it safe to assume...", I think is definitely no, REMOTE_ADDR can not be trusted.

As far as I know it is reported to PHP from the server, in my case Apache. Why it was bad I am still trying to figure out. I do know this. It came in as part of a batch of attack requests. Sometimes it was 183.60.244.37 and sometimes it was 183.60..244.37.

See also this.

Elliptical view
  • 3,338
  • 1
  • 31
  • 28
  • Nice to know, probably some Apache bug no? – Alix Axel Feb 09 '14 at 06:34
  • A php developer just told me REMOTE_ADDR comes from cgi and so from the server's tcp connection, and not http. But I'm still working on finding how the server could be reporting this to php, if that is what is happening. – Elliptical view Feb 09 '14 at 06:58