2010-12-09 49 views
0

我有一個mac地址字符串(沒有':'在其中)我需要計算第二個下一個地址。如何通過定義的值增加MAC地址?

我tryed到:

$macDec = hexdec($mac); 
$macDec += 2; 
$newMac = dechex($macDec); 

但這修剪十進制值爲整數的範圍和計算出的MAC是不正確的,我可以比使用BC數學等什麼簡單的辦法做到這一點?

+1

究竟是爲了什麼? MAC地址通常是完全隨機的(除非你是製造商,並且有一批相同的產品) – 2010-12-09 15:49:27

回答

1

行,我發現了一個解決方案,因爲實際上每個供應商有權使用其自己的廠商ID,和標準,MTA MAC是調制解調器MAC + 2 i。從MAC剝離廠商ID部分,做一個簡單的計算,並前置VENDORID

function mac2mtaMac($mac) { 
    $mac = preg_replace('/[^0-9A-Fa-f]/', '', $mac); 
    $macVendorID = substr($mac, 0, 6); 
    $macDec = hexdec(substr($mac, 5)); 
    $macDec += 2; 
    $macHex = dechex($macDec); 
    $mtaMac = $macVendorID.str_repeat('0', 6 - strlen($macHex)).$macHex; 
    return $mtaMac; 
} 

@保羅諾曼:THX關於如何做到這一點很快

2
$mac = increment_mac('00:00:00:00:00:fe', 2); 

function increment_mac($mac_address, $increment = 1, $return_partition = ':') 
{ 
    $mac_address = preg_replace('![^0-9a-f]!', '', $mac_address); 

    $parts = str_split($mac_address, 2); 
    foreach($parts as $i => $hex) 
    { 
     $parts[$i] = hexdec($hex); 
    } 

    $increase = true; 
    if($increment < 0) 
    { 
     $increase = false; 
    } 

    $parts[5] += $increment; 
    for($i = 5; $i >= 1; $i--) 
    { 
     if($increase) 
     { 
      while($parts[$i] > 255) 
      { 
       $parts[$i] -= 256; 
       $parts[$i - 1] += 1; 
      } 
     } 
     else 
     { 
      while($parts[$i] < 0) 
      { 
       $parts[$i] += 256; 
       $parts[$i - 1] -= 1; 
      } 
     } 
    } 

    foreach($parts as $i => $dec) 
    { 
     $parts[$i] = str_pad(dechex($dec), 2, 0, STR_PAD_LEFT); 
    } 

    return implode($return_partition, $parts); 
} 
0

不要重新發明輪子,用netaddr中庫的一些提示。我寫這個來根據序列號範圍生成一個MAC地址列表。

from netaddr import * 

# Create a list of serial numbers that need MAC addresses 
# 
sns=range(40125, 40192) 

# Create a MAC address and seed it with the first available MAC address then convert 
# that MAC address to an integer for easy math 
# 
mac = EUI('00-11-22-33-02-D7').value 

# Assign a MAC address to every serial number 
# 
for i in range(len(sns)): 
    # Notice that we are creating a MAC address based on an integer 
    # 
    print "{0},{1}".format(sns[i], str(EUI(mac+i)).replace('-',' '))