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

后端 未结 12 2644
后悔当初
后悔当初 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条回答
  •  Happy的楠姐
    2020-11-30 07:58

    Also you could get IP via DNS A record based on hostname or server name:

    $dnsARecord = dns_get_record($_SERVER['HTTP_HOST'],DNS_A);
    if ( $dnsARecord ) echo 'IPv4: '.$dnsARecord[0]['ip'];
    $dnsARecord = dns_get_record($_SERVER['HTTP_HOST'],DNS_AAAA);
    if ( $dnsARecord ) echo 'IPv6: '.$dnsARecord[0]['ip'];
    

    You could also use SERVER_NAME instead of HTTP_HOST if one of the two does not give what you want.

    However, this is assuming that your server is configured correctly in correspondence with DNS. This may not always be the case. See my other answer using ifconfig that is perhaps better.

提交回复
热议问题