PHP獲取MAC地址

參考文章:http://www.cnblogs.com/nackman/archive/2012/07/22/2603443.html

說明:
我在自己使用後,對源碼進行了部分更改,原始代碼請參考原文;
我只在win7和Ubuntu上測試過

源碼如下:
<?php

class GetMacAddr{

    var $return_array = array(); // 返回帶有MAC地址的字串數組
    var $mac_addr = array();

    function GetMacAddr($os_type){
        switch ( strtolower($os_type) ){
            case "linux":
                $this->forLinux();
                break;
            case "solaris":
                break;
            case "unix":
                break;
            case "aix":
                break;
            default:
                $this->forWindows();
                break;
        }


        $temp_array = array();//數組,用來保存匹配正則表達式的mac地址

        //用來匹配mac地址的正則表達式
        $preg_string = "/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]".
            "[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]".
            "[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i";


        foreach ( $this->return_array as $value )
        {

            if (preg_match($preg_string, $value, $temp_array ) )
            {

                array_push( $this->mac_addr, $temp_array[0]);
            }

        }

        unset($temp_array);
        return $this->mac_addr;
    }


    //獲取運行Windows操作系統的計算機mac地址
    function forWindows(){
        @exec("ipconfig /all", $this->return_array);
        if ( $this->return_array )
            return $this->return_array;
        else{
            $ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe";

            if ( is_file($ipconfig) )
                @exec($ipconfig." /all", $this->return_array);
            else
                @exec($_SERVER["WINDIR"]."\system\ipconfig.exe /all",
                    $this->return_array);
        }
    }

    //獲取運行Linux操作系統的計算機mac地址
    function forLinux(){
        @exec("ifconfig -a", $this->return_array);

    }

}
?>

GetMacAddr類的使用方法:
include 'getMacAddr.php';
$mac = new GetMacAddr('windows');
echo $mac->mac_addr[0];//此處數組下標根據實際情況定。
                        //在win7下存在不止一個本地網絡連接的時候,就要自己來確定哪個是真正的MAC地址。


我在Linux上部署遇到的問題:exec() has been disabled for security reasons in ....
原因:出於安全考慮,php禁用了exec()函數。
參考:http://blog.csdn.net/hnllc2012/article/details/48649837


解決方法:修改php.ini,使exec()可用。
參考:http://blog.csdn.net/hnllc2012/article/details/48649607


補充:windows系統下,獲取MAC地址也可以使用getmac命令。有興趣話的可以自己嘗試下。


不同系統下獲取MAC地址的方法:http://www.unixmantra.com/2013/04/how-to-finddisplay-your-mac-address.html








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章