PHP how to get local IP of system

2020-01-24 11:31发布

I need to get local IP of computer like 192.*.... Is this possible with PHP?

I need IP address of system running the script, but I do not need the external IP, I need his local network card address.

15条回答
何必那么认真
2楼-- · 2020-01-24 11:34

try this (if your server is Linux):

$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command);
echo $localIP;
查看更多
Deceive 欺骗
3楼-- · 2020-01-24 11:34

If you are in a dev environment on OS X, connected via Wifi:

echo exec("/sbin/ifconfig en1 | grep 'inet ' | cut -d ' ' -f2");
查看更多
爷、活的狠高调
4楼-- · 2020-01-24 11:35
$_SERVER['REMOTE_ADDR']
  • PHP_SELF Returns the filename of the current script with the path relative to the root

  • SERVER_PROTOCOL Returns the name and revision of the page-requested protocol

  • REQUEST_METHOD Returns the request method used to access the page

  • DOCUMENT_ROOT Returns the root directory under which the current script is executing

查看更多
姐就是有狂的资本
5楼-- · 2020-01-24 11:37

This is an old post, but get it with this:

function getLocalIp()
{ return gethostbyname(trim(`hostname`)); }

For example:

die( getLocalIp() );

Found it on another site, do not remove the trim command because otherwise you will get the computers name.

BACKTICKS (The special quotes): It works because PHP will attempt to run whatever it's between those "special quotes" (backticks) as a shell command and returns the resulting output.

gethostbyname(trim(`hostname`));

Is very similar (but much more efficient) than doing:

$exec = exec("hostname"); //the "hostname" is a valid command in both windows and linux
$hostname = trim($exec); //remove any spaces before and after
$ip = gethostbyname($hostname); //resolves the hostname using local hosts resolver or DNS
查看更多
叼着烟拽天下
6楼-- · 2020-01-24 11:38

hostname(1) can tell the IP address: hostname --ip-address, or as man says, it's better to use hostname --all-ip-addresses

查看更多
做自己的国王
7楼-- · 2020-01-24 11:38
$localIP = gethostbyname(trim(exec("hostname")));

I tried in Windows pc and Its worked and also think that Will work on Linux to.

查看更多
登录 后发表回答