PHP跨平台获取服务器IP地址自定义函数分享
近期为了完善日志机制,需要监控来自不同服务器上的机器所执行的脚本状态,因此专门编写了一个函数,以兼容Windows和Linux系统,同时支持Web应用与命令行两种运行模式。
为实现上述需求,编写了以下函数代码:
复制代码 代码如下: function getServerAddr() { //运行 web app if (isset($_SERVER["SERVER_ADDR"])) { return $_SERVER["SERVER_ADDR"]; } else { // Running CLI if (stristr(PHP_OS, 'WIN')) { // 针对windows服务器所执行的一种hacky方式 exec("ipconfig /all", $catch); foreach ($catch as $line) { $new_catch[] = iconv("gbk", "utf-8", $line) . "\n"; } foreach ($new_catch as $new_line) { if (preg_match(‘/IPv4 地址/', $new_line)) { //中文系统 list($t, $ip) = explode(‘:', $new_line); $ip = trim($ip); preg_match(‘/((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))/', $ip , $match); return $match[1]; } } } else { $ifconfig = shell_exec(‘/sbin/ifconfig eth0′); preg_match(‘/addr:([\d\.]+)/', $ifconfig, $match); return $match[1]; } } } $ip = getServerAddr(); print $ip;