PHP cli获取当前服务器ip地址

网上很多用法都试过,不行的。
有的用ifconfig,但是有的Linux系统默认是不安装ifconfig的,但是ip a是有的。下面我们用ip a来获取服务器ip地址

  1. 命令
ip a

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: enp9s0f0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether d4:3d:7e:75:99:1c brd ff:ff:ff:ff:ff:ff
    inet 100.200.30.81/27 brd 100.200.30.81 scope global noprefixroute enp9s0f0
       valid_lft forever preferred_lft forever
    inet6 fe80::48ea:700d:7747:1faa/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
3: enp9s0f1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether d4:3d:7e:75:99:1d brd ff:ff:ff:ff:ff:ff

  1. 网口各不相同,不能过滤网口,ip所在行有共同字段 inet,通过inet获取各行
ip a | grep 'inet'

    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host 
    inet 100.200.30.81/27 brd 100.200.30.81 scope global noprefixroute enp9s0f0
    inet6 fe80::48ea:700d:7747:1faa/64 scope link noprefixroute 
    inet6 fe80::afea:d3ad:ee20:3b82/64 scope link noprefixroute 

  1. 上面发现了多行,实际上我们只需要 100.200.30.81,过滤inet6
ip a | grep 'inet' | grep -v inet6

    inet 127.0.0.1/8 scope host lo
    inet 100.200.30.81/27 brd 100.200.30.81 scope global noprefixroute enp9s0f0

  1. 127.0.0.1很明显不是我们想要的,过滤掉
ip a | grep 'inet' | grep -v inet6 | grep -v 127*

inet 100.200.30.81/27 brd 100.200.30.81 scope global noprefixroute enp9s0f0
  1. 我们只需要ip,不需要其他多余字符,ip在字段中有两个地方展示:
    inet 100.200.30.81/27 表示ipv4地址
    brd 100.200.30.81 表示广播地址
    这里我们要的是ipv4地址
ip a | grep 'inet' | grep -v inet6 | grep -v 127* | awk '{print $2}'

100.200.30.81/27
  1. 只想要 ip
ip a | grep 'inet' | grep -v inet6 | grep -v 127* | awk '{print $2}'|awk -F '/' '{print $1}'

100.200.30.81

最终获取ip通用命令:

ip a | grep 'inet' | grep -v inet6 | grep -v 127* | awk '{print $2}'|awk -F '/' '{print $1}'

php 调用shell执行,获取ip地址返回:

$serverIP = exec("ip a | grep 'inet' | grep -v inet6 | grep -v 127* | awk '{print $2}'|awk -F '/' '{print $1}'");

封装方法:

function getServerIp(){
	return exec("ip a | grep 'inet' | grep -v inet6 | grep -v 127* | awk '{print $2}'|awk -F '/' '{print $1}'");
}

你可能感兴趣的:(PHP,运维)