Nasıl CLI'den PHP kullanarak sunucu IP adresi alabilirsiniz?

5 Cevap

Başlık hemen hemen özetliyor:

Nasıl CLI'den PHP kullanarak sunucu IP adresi alabilirsiniz?

PHP'nin CLI kullanarak, $ _SERVER sunucunun IP adresi içermiyorsa, bu yüzden bariz çözüm söz konusu değildir.

Teşekkürler!

5 Cevap

Şey CLI PHP çalışırken, herhangi dahil hiçbir ağ etkinliği yok IP adresleri dolayısıyla, var, olduğunu. Ilk ve tanımlamanız gerekir Ne şeyden isimli, what almak istediğiniz IP.

  • The IP of the client running the script?
    Not possible, since there is no "client".

  • The local IP of a network interface?
    Run some system utility like ifconfig, but you may get more than one IP if the server has more than one network interface.

  • The IP of a domain, which may or may not correspond to the server you're running on?
    Use gethostbyname(), but you need to know which domain you want to query for.

  • The public facing IP of the network/server you're on?
    You'll need to use an external service like www.whatsmyip.org (note that they don't like this) which will tell you what IP your request came from. Whether this address corresponds to anything useful is a different topic.

Eğer $_SERVER['REMOTE_ADDR'] veya $_SERVER['SERVER_ADDR'], sadece bir CLI-çalıştırmak komut için geçerli değildir ilgileniyorsanız eğer alt çizgi vardır.

Bu kod bit * nix sistemde arayüz "eth0" IP adresi alacaktır.

// get the local hosts ip address
$hostsipaddress = str_replace("\n","",shell_exec("ifconfig eth0 | grep 'inet addr' | awk -F':' {'print $2'} | awk -F' ' {'print $1'}"));

Eğer ifconfig () gibi veya exec (), bir kabuk programı pass_thru sürece noktada PHP IP bilmiyor. Ben bu amaç için CLI kullanarak yeniden öneririz.

Bu durumda "Temel tercüman" olarak PHP CLI düşünün.

Ben PHP ile bir bağlantı tutarken bir PHP CLI dosyası arayarak varsayarak yaşıyorum. Bu durumda ise, bir komut satırı argümanı olarak CLI komut dosyası $ _SERVER değerini geçebileceği.

Ben burada hızla araya işlevi olduğunu için bu süre arama bulundu beri. Daha iyi hata denetimi ve böyle kullanın ama iş yok olabilir. Belki diğerleri de yararlı bulabilirsiniz:

function get_external_ip() {
    $ch = curl_init("http://icanhazip.com/");
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    if ($result === FALSE) {
        return "ERROR";
    } else {
        return trim($result);
    }
}