I'm working with an API that requires the machine's external IP. As far as I know, the PHP environment I'm using can only get our internal IP.
The option on the table is using an external service such as whatismyip.com to tell us:
wget -q -O - http://whatismyip.com/automation/n09230945.asp
My concern is what happens if that fails. Is there a bulletproof way of determining a machine's IP without relying on external services?
No. Because NAT is supposed to be transparent that pertty much rules out doing anything you can do on the computer itself. You can bet (check IP addresses against defined private areas) but this is not bullet proof either.
This would be more of a question for StackOverflow, but I'll bite anyway! Presuming there's no Port Forwarding or load balancing involved, you can use the
$_SERVER['SERVER_ADDR']
variable to get the ip that the script is running on.Another gotcha is that it might not be the ip that any connections from the script are going out from. Take for example if you have a server with a primary ip of 192.0.2.1, and a secondary ip of 192.0.2.2 for an SSL site on which the script is running. When you use the variable above, the ip returned will be 192.0.2.2, but when you create an outbound connection in the sciprt, it will be from 192.0.2.1 unless you specifically bind to 192.0.2.2.
because you say internal and external I assume that you use some sort of firewall that does nat for you. if this is the case is impossible to tell from your local script what ip you have, this is because once the network packets leave your box you can't tell what it will happen.
a simple solution is to use a few servers that are external (some free hosting) or have an external server that you call from php and returns you the ip address, as pointed out the array SERVER holds this info. if you have more then one server you can call the next and so on.
You could set up another server with a different ISP and write your own version of whatismyip.com, running on hardware that you control.
Your best bet is to use more than one external source for your IP information. In addition to whatismyip most, if not all, DDNS providers (e.g. DynDNS) have a similar service. If you can't get the information from one site simply try the next one in the list.