开发者

How to increase of MAC address by a defined value?

I have a mac address string (without ':' in it) I need to calculate second next address.

I've tryed to:

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

but this trims decimal value to integer range and calculated mac is incorrect, can i do this in 开发者_开发百科any simple way than using BC Math etc. ?


$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);
}


OK, i found a solution, because of fact that each vendor has to use its own VendorID, and standard that MTA MAC is Modem MAC + 2 i strip vendorID part from mac, do a simple calculation, and prepend 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;
}

@Paul Norman: thx for few hints on how to do that quickly


Don't reinvent the wheel, use the netaddr library. I wrote this to generate a list of MAC addresses based on a serial number range.

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('-',' '))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜