繁体   English   中英

如何在 PHP(CLI) 中找到我的服务器的 IP 地址

[英]How do I find my server's IP address in PHP(CLI)

除了显而易见的(本地主机,127.0.0.1)之外,PHP(命令行界面?)是否有一种机制可以发现运行脚本的计算机的 IP?

$_SERVER[*]将不起作用,因为这不是 Web 应用程序 - 这是一个命令行脚本。

TIA

您可以使用gethostname获取主机名

试试这个它应该返回服务器的IP地址

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

如果您使用 PHP < 5.3,这可能会有所帮助(至少在基于 *NIX 的系统上):

 mscharley@S04:~$ cat test.php
#!/usr/bin/env php
<?php

function getIPs($withV6 = true) {
    preg_match_all('/inet'.($withV6 ? '6?' : '').' addr: ?([^ ]+)/', `ifconfig`, $ips);
    return $ips[1];
}

$ips = getIPs();
var_dump($ips);

 mscharley@S04:~$ ./test.php
array(5) {
  [0]=>
  string(13) "72.67.113.141"
  [1]=>
  string(27) "fe80::21c:c0ff:fe4a:d09d/64"
  [2]=>
  string(13) "72.67.113.140"
  [3]=>
  string(9) "127.0.0.1"
  [4]=>
  string(7) "::1/128"
}
 mscharley@S04:~$

或者,如果您不希望经常这样做,那么也许这会起作用(只是不要滥用它):

$ip = file_get_contents('http://whatismyip.org/');

我知道这是一个相当古老的问题,但似乎没有明确的答案(尽可能多)。我需要在 *NIX 框和 Win X 上确定这个值盒子。 同样来自 CLI 执行的脚本以及非 CLI 脚本。 以下函数是我想出的最好的函数,它借鉴了人们多年来谈论的不同概念。 也许它可以有一些用处:

function getServerAddress() {
    if(isset($_SERVER["SERVER_ADDR"]))
    return $_SERVER["SERVER_ADDR"];
    else {
    // Running CLI
    if(stristr(PHP_OS, 'WIN')) {
        //  Rather hacky way to handle windows servers
        exec('ipconfig /all', $catch);
        foreach($catch as $line) {
        if(eregi('IP Address', $line)) {
            // Have seen exec return "multi-line" content, so another hack.
            if(count($lineCount = split(':', $line)) == 1) {
            list($t, $ip) = split(':', $line);
            $ip = trim($ip);
            } else {
            $parts = explode('IP Address', $line);
            $parts = explode('Subnet Mask', $parts[1]);
            $parts = explode(': ', $parts[0]);
            $ip = trim($parts[1]);
            }
            if(ip2long($ip > 0)) {
            echo 'IP is '.$ip."\n";
            return $ip;
            } else
            ; // TODO: Handle this failure condition.
        }
        }
    } else {
        $ifconfig = shell_exec('/sbin/ifconfig eth0');
        preg_match('/addr:([\d\.]+)/', $ifconfig, $match);
        return $match[1];
    }
    }
}

如果所有其他方法都失败了,您可以始终执行ipconfig 或 ifconfig,具体取决于您的平台,并解析结果。

如果您想查找本地 ip v4 而不是 WSL 地址。

感谢https://stackoverflow.com/users/272555/impressthenet-web-developer提供https://stackoverflow.com/a/6256719/15610724
我重写了 Windows 10 和 php 7.4 的代码:

function getServerAddrAndName() {
  $serverName = getHostName();
  $addr = 'unknown';

  if (stristr(PHP_OS, 'WIN')) {
    // WIN 10 checked
    $lines = [];
    exec('ipconfig', $lines);
    // print_r($lines);
    $inWsl = FALSE;
    foreach($lines as $i => $line) {
      if ($line && stripos($line, '  ') !== 0) {
        // header-information
        $inWsl = stripos($line, '(WSL)');
        continue;
      }
      if (!$line || $inWsl) {
        // information is null or from WSL connect
        continue;
      }
      if ((stripos($line,'IP Address') || stripos($line, 'IPv4 Address')) && stripos($line,':')) {
        [, $ip] = explode(':', $line);
        $matches = [];
        $reg = '/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/';
        if (preg_match($reg, $ip, $matches)) {
          [$ip] = $matches;
          if (filter_var($ip, FILTER_VALIDATE_IP)) {
            $addr = $ip;
            break;
          }
        }
      }
    }
  } else {
    // Ubuntu 20.04 checked
    $addr = shell_exec("ip addr show eth0 | grep \"inet\b\" | awk '{print $2}' | cut -d/ -f1");
  }

  return ['serverAddr' => $addr, 'serverName' => $serverName];
}

$ip = file_get_contents(' http://icanhazip.com/ ');

回声 $ip;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM