5

assuming that php is running in web mode via cgi / mod_php / etc...

is it safe to assume that $_SERVER['REMOTE_ADDR'] will exist, and further more, that it will contain a correctly stylized (sorry, terminology may be off here...) ip (1.1.1.1 -> 255.255.255.255?)?

this is not a question regarding weather the ip contained inside $_SERVER['REMOTE_ADDR'] will be a the true ip of the client making the request, as i do understand this can be 'spoofed' by modifying the outbound tcp packets...

just simply:

a) will $_SERVER['REMOTE_ADDR'] always exist if php is ran in web mode. b) if $_SERVER['REMOTE_ADDR'] does always exist, will it always contain a properly syntaxed ip?

thanks.

anonymous-one
  • 14,454
  • 18
  • 60
  • 84
  • Good question - I think the answer is "yes" on both counts, but I'm not totally sure about [IPV6](http://en.wikipedia.org/wiki/IPV6). Out of curiosity, why do you need to know? At which point would you get into trouble if it were *not* a properly formatted IP? – Pekka Jun 25 '11 at 14:05
  • just going over code that has been running (running, well) for years, but has been validating this information via: isset($_SERVER....) + ^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}^ this appears to be completely unnecessary – anonymous-one Jun 25 '11 at 14:11
  • as far as ipv6 compliance... ipv6 is disabled on the box running this code, so were ok (for the time being) on that front... thanks again! – anonymous-one Jun 25 '11 at 14:13

1 Answers1

6

Yes, it is always present in web mode, and since the IP address is converted from its binary representation to the textual format you're seeing, it is always valid – there is no way to specify an invalid IP in the IP header.

One more thing: Don't assume any special format unless you absolutely must deal with IP addresses. For example, IPv6 addresses are longer and contain different characters. Basically, deal with IP addresses as an opaque string.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • I'm aware that this is over a year old. But, I run a server that uses ip2long to store information about each visit in a database. My code is `$ip = ip2long($_SERVER['REMOTE_ADDR'])`, and I have found $ip to equal 0. Why would that happen? – Kayla Oct 02 '13 at 21:13
  • Nevermind my last comment. My database wasn't accepting negative numbers. **Be aware, ip2long can return a negative.** – Kayla Oct 02 '13 at 21:25
  • 1
    @WaffleStealer654 `ip2long` is a legacy function and should not be used. By using it, you are intentionally introducing a bug in your application, as it will not work with IPv6 anymore. Either use a text field or use your [database's IP address support](http://stackoverflow.com/q/6964143/35070) – phihag Oct 03 '13 at 09:56