最近要用用php代码获取机器的ip地址, 先来写个:
- <?php
-
- function get_machine_ip()
- {
- $result = shell_exec("/sbin/ifconfig");
- if (preg_match_all("/inet (\d+\.\d+\.\d+\.\d+)/", $result, $match) !== 0) // 这里根据你机器的具体情况, 可能要对“inet ”进行调整, 如“addr:”,看如下注释掉的if
- // if (preg_match_all("/addr:(\d+\.\d+\.\d+\.\d+)/", $result, $match) !== 0)
- {
- foreach( $match [0] as $k => $v )
- {
- if ($match [1] [$k] != "127.0.0.1")
- {
- $the_local_ip = $match [1] [$k];
- return $match [1] [$k];
- }
- }
- }
-
- return "0.0.0.0";
- }
-
- $ip = get_machine_ip();
- var_dump($ip);
-
- ?>
试了一把, 靠谱。