PHP代码:MAC地址数字互转
/** * mac合法性校验 兼容大小写和(:-) * @param $mac * @return bool */ protected function mac_check($mac) { if (empty($mac)) { return FALSE; } $mac_reg = '/^([0-9a-fA-F]{2})((([:][0-9a-fA-F]{2}){5})|(([-][0-9a-fA-F]{2}){5}))$/i'; return preg_match($mac_reg, $mac) == 1 ? TRUE : FALSE; } /** * mac 转化为数字表示 * @param $mac_str * @return bool|number */ protected function mac_to_int($mac_str) { if (!$this->mac_check($mac_str)) return FALSE; $filter_mac = strtolower(preg_replace('/[:-]/', '', $mac_str)); $mac_int = hexdec($filter_mac); if (is_numeric($mac_int)) return $mac_int; else return FALSE; } /** * 数字转换为标准mac * @param $mac_int * @param string $chain ('-', ':') * @return bool|string */ protected function int_to_mac($mac_int, $chain = '-') { $max_value = 281474976710655; $min_value = 0; if (!is_numeric($mac_int) || $mac_int > $max_value || $mac_int < $min_value) return FALSE; $chain_list = array('-', ':'); if (!in_array($chain, $chain_list)) return FALSE; $mac_hex = dechex($mac_int); $mac_str = strval($mac_hex); $mac_hex_len = strlen($mac_hex); if ($mac_hex_len < 12) { $add_len = 12 - $mac_hex_len; $add_str = ''; while ($add_len--) { $add_str .= '0'; } $mac_str = $add_str . $mac_str; } $mac_arr = str_split($mac_str, 2); $mac_full_str = implode($chain, $mac_arr); if (!$this->mac_check($mac_full_str)) { return FALSE; } else { $res = str_replace("-", ":", strtoupper($mac_full_str)); return $res; } }
THE END