How do I get the external IP of my server using PHP?

后端 未结 12 2639
后悔当初
后悔当初 2020-11-30 07:47

I often hear people say to use \"$_SERVER[\'SERVER_ADDR\']\", but that returns the LAN IP of my server (e.g. 192.168.1.100). I want the external IP.

12条回答
  •  渐次进展
    2020-11-30 08:12

    I'm going to add a solution because the others weren't quite right for me because they:

    • need to be run on a server with a domain name e.g. gethostbyname() (if you think about it, you don't actually have the problem if you know this a priori)
    • can't be used on the CLI (rely on something in $_SERVER to be set by a web server)
    • assume a specific format of ifconfig output, which can include multiple non-public interfaces
    • depend on parsing someone's website (who may disappear, change the URL, change the format, start lying to you, etc, all without notice)

    This is what I would suggest:

    $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    $res = socket_connect($sock, '8.8.8.8', 53);
    // You might want error checking code here based on the value of $res
    socket_getsockname($sock, $addr);
    socket_shutdown($sock);
    socket_close($sock);
    
    echo $addr; // Ta-da! The IP address you're connecting from
    

    The IP address there is a Google public DNS server. I trust they'll be around and running it for a while. It shouldn't really matter what address you use there as long as its a public IP address that belongs to someone who doesn't mind random connection attempts too much (yourself maybe?).

    This is based on an answer I came across when I had a similar problem in Python.


    P.S.: I'm not sure how well the above would work if there is sorcery going on between your machine and the internet.

提交回复
热议问题