0

I making MAC addr generator and currently I have this problem.

mac1="001122334455"
mac2="001122334695"

mac1 = [mac1[x:x+2] for x in xrange(0,len(mac1),2)]
mac2 = [mac2[x:x+2] for x in xrange(0,len(mac2),2)]
k=0
for item in mac1:
    mac1[k] = "%d" % int(mac1[k], 16)
    mac2[k] = "%d" % int(mac2[k], 16)
    mac1[k]=int(mac1[k])
    mac2[k]=int(mac2[k])
    k=k+1

while mac1 != mac2:
    #print mac1

    print "%X0:%X:%X:%X:%X:%X" % (mac1[0], mac1[1], mac1[2], mac1[3], mac1[4], mac1[5])
    mac1[5] = int(mac1[5]) + 1
    if int(mac1[5]) > 255:
        #mac1[5] = 00
        mac1[4] = int(mac1[4]) +1
        if int(mac1[4]) > 255:
            mac1[3] = int(mac1[3]) + 1
            if int(mac1[3]) > 255:
                mac1[2] = int(mac1[2]) +1
                if int(mac1[2]) > 255:
                    mac1[1] = int(mac1[1]) +1

I need to start generating fifth byte from beginning so I defined mac1[5] = 00, but instead of two 0 I only get one 0?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Thomas
  • 121
  • 2
  • 3
  • 8
  • Replace `"%X0:%X:%X:%X:%X:%X"` with `"%02X:%02X:%02X:%02X:%02X:%02X"` - but also see my a little bit shorter solution. – eumiro Dec 07 '11 at 11:18
  • It's easier to take string slices than to do a bunch of shifts and mods - see solution below. – Dave Dec 07 '11 at 12:14

2 Answers2

0

You cannot set an integer as 00 it will always degrade to 0, added to that fact, in python 2.x putting a 0 in front of an integer (for example 0123) will tell python you want that number evaluated as an octal! defiantly not what you want. In python 3.x, 0integer is not allowed at all!

you need to use strings if you want 00 instead of 0.

Out of interest, are you trying to generate a range of macs between mac1 and mac2, if so I suspect i have a more elegant solution if you are interested.


EDIT:

Working solution will print the hex values of the mac address between start and finish, since it works internally with integers between 0 and 255 the start and end values are integers not hex values.

start = [0,11,22,33,44,55]
end =   [0,11,22,33,46,95]

def generate_range(start, end):
    cur = start

    while cur < end:     
        cur[5] = int(cur[5]) + 1

        for pos in range(len(cur)-1, -1, -1):
            if cur[pos] == 255:
                cur[pos] = 0
                cur[pos-1] = int(cur[pos-1]) + 1

        yield ':'.join("{0:02X}".format(cur[i]) for i in range(0,len(cur)))

for x in generate_range(start, end):
    print (x)
Serdalis
  • 10,296
  • 2
  • 38
  • 58
0

Much simpler to just treat the entire mac as one number:

mac1 = 0x1122334455
mac2 = 0x1122334695
for i in xrange(mac1, mac2+1):
    s = "%012x" % i
    print ':'.join(s[j:j+2] for j in range(0,12,2)))

See Display number with leading zeros

Community
  • 1
  • 1
Dave
  • 3,834
  • 2
  • 29
  • 44