I am running a stand-alone PHP script outside of the Apache environment, so I cannot use the $_SERVER['SERVER_ADDR'] variable. My question is, How do I get the server's IP address? Anyone have any ideas?

    Never mind. I found it:

    $host= gethostname();
    $ip = gethostbyname($host);
    

      Only other question left to answer is... which IP address did you want? 😉

        While the scriptlet above works for me, how would it work if the server had more than one IP attached to it? Just curious...

          Well first let me describe my primary home computer so you can see what I envisioned. It has 2 NICs, but it essentially has 6 IP addresses it can use to refer to itself. The first two are the easy guesses: "::1" and "127.0.0.1" (remember, IPv4 is dying - IPv6 is the wave of the future! :p).

          Next, one of the NICs connects to my public-facing router, and it is assigned another two IPs - "10.0.1.1" and a private IPv6 address (lets call it "FDC8:BF8B:E62C:ABCD:1111:2222:3333:4444"). In addition, the computer is configured as the DMZ host on the router, so my public IP address (lets call it 123.456.78.9) also routes to my computer (in the corporate setting, pretend this is just an external IP NAT'ed to an internal one).

          Finally, my second NIC connects directly to a *nix box using IPv6 only, thus it has only one IP address (lets call it "FE80::903A:1C1A:E802:11E4").

          Since your proposed solution above uses [man]gethostbyname/man, we can rule out the three IPv6 addresses above. Note that this completely eliminates my second NIC. Next, we can probably rule out the localhost IPv4 address since the server should always know its own hostname (tangent: wonder what would happen if I named my computer "localhost" ...).

          So now we're just left with my external IP (of which, in the setup(s) I described above, my local machine has no knowledge), and one of my internal IPs. Your code does indeed pick the latter, but without knowing what the purpose/application behind the question you posed above, perhaps that's not the IP address I was looking for.

            Write a Reply...