Read 1009 times | Created 2013-01-15 04:02:20 | Updated 2013-01-15 04:38:02 | | |

 

<?php
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(stristr($line,'IPv4 Address')) {
          // Have seen exec return "multi-line" content, so another hack.
          if(count($lineCount = explode(':', $line)) == 1) {
            list($t, $ip) = explode(':', $line);
            $ip = trim($ip);           
          } else {
            $parts = explode('IPv4 Address', $line);
            $parts = explode('Subnet Mask', $parts[1]);
            $parts = explode(': ', $parts[0]);
            $ip = trim($parts[1]);
          }
          if(ip2long($ip > 0)) {
            return $ip;
          } else {
            return gethostbyname(gethostname());
          }
        }
      }
    } else {
      $ifconfig = shell_exec('/sbin/ifconfig eth0');
      preg_match('/addr:([d.]+)/', $ifconfig, $match);
      return $match[1];
    }
  }
}

function get_ip( $host ){ 
  $hostip = @gethostbyname( $host ); 
  $ip = ( $hostip == $host ) ? $host : long2ip( ip2long( $hostip ) ); 
  return $ip; 
} 

echo getServerAddress();
?>