user2424531 February 2016

How to convert MAC address to a link-local IPV6 address in TCL

I am trying to convert a MAC address to a link-local IPV6 address using TCL. I have a code snippet that works well for all integer based MAC address but not for hex based like the ones, especially those that start with an non-numeral character. My current code:

set newmac AC:DE:48:1D:27:6D

lassign $newmac __o1 __o2 __o3 __o4 __o5 __o6

set __o1 [expr $__o1 ^ 0x02]  ;# universal bit flip

set __ip fe80::${__o1}${__o2}:${__o3}ff:fe${__o4}:${__o5}${__o6}

The bit flipping/inverting part does not work for this address, as I think the expr always expects a integer, although the same code works fine for other addresses like example - 55:12:34:26:21:97

Can anybody suggest me a way to improve this code that works for all cases?

Answers


Brad Lanam February 2016

First, the lassign as you have it will not work. I have included the original lassign in the code below so you can see what happens. You would have wanted:

lassign [split $newmac :] __o1 __o2 __o3 __o4 __o5 __o6

to achieve what you wanted. You are completely correct that expr expects integers. Use the scan command to scan the hex values from your string. and then use format to convert back to hex.

set newmac AC:DE:48:1D:27:6D
lassign $newmac __o1 __o2 __o3 __o4 __o5 __o6
puts "$__o1 - $__o2 - $__o3 - $__o4 - $__o5 - $__o6"
scan $newmac {%02x:%02x:%02x:%02x:%02x:%02x} __o1 __o2 __o3 __o4 __o5 __o6
puts "$__o1 $__o2 $__o3 $__o4 $__o5 $__o6"
set __o1 [expr $__o1 ^ 0x02] ;# universal bit flip
set __ip [format {fe80::%02x%02x:%02xff:fe%02x:%02x%02x} \
    $__o1 $__o2 $__o3 $__o4 $__o5 $__o6]
puts "$__ip"

Output:

AC:DE:48:1D:27:6D -  -  -  -  - 
172 222 72 29 39 109
fe80::aede:48ff:fe1d:276d

Post Status

Asked in February 2016
Viewed 3,700 times
Voted 6
Answered 1 times

Search




Leave an answer