Hi,,
Is it possible to get IP of server where the script is running.
I used following code

<?php 
echo $ip=$_SERVER['REMOTE_ADDR'];
echo  $_SERVER['SERVER_ADDR'];
?>

But it outputing as "127.0.0.1".
Is there any way to print IP ?

Dani AI

Generated

Short answer: yes — but 127.0.0.1 is usually the correct result when the browser and the PHP process are on the same machine or when the webserver is bound only to the loopback interface. 's posted values come from the webserver/PHP environment: the client IP will be the loopback when accessed locally, and the server-address entry is not guaranteed to be populated by every SAPI (as noted).

A reliable way to discover which local IP the server will use for outbound connections is to ask the OS which local address would be used for a UDP connection (no data needs to be sent). Example using streams:

$fp = stream_socket_client('udp://8.8.8.8:53', $errno, $errstr, 1);
if ($fp) {
    $local = stream_socket_get_name($fp, false); // returns "ip:port"
    $ip = explode(':', $local)[0];
    echo $ip;
    fclose($fp);
}

Simpler fallbacks exist but have caveats. gethostbyname(gethostname()) often returns the host’s configured address, but it can resolve to a loopback address if /etc/hosts maps the hostname to 127.x.x.x. To obtain the public/WAN IP (the address seen from the Internet) a server-side call to an external service (for example via file_get_contents('https://api.ipify.org')) is required — that returns the public IP but depends on outbound connectivity and an external dependency.

Troubleshooting checklist: confirm whether the server is running on localhost or inside a VM/container; inspect webserver bind/listen settings (Apache/Nginx); check /etc/hosts for hostname mappings; remember that behind NAT or a load balancer the machine’s LAN IP is not the public IP. For script-only environments, prefer the UDP/stream method or an external public-IP service depending on whether an internal or external address is needed.

That will only work if running in (Fast)CGI. See the last entry in this thread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.