n2x packets and protocols - warsaw university of...
TRANSCRIPT
N2X Packets and Protocols
—Tcl Primer
Page 2
About Tcl/Tk
• Tcl: Tool Command Language
• very simple scripting language
• can source scripts or enter commands interactively
• Tcl interpreter: parses commands and scripts
• Tcl shell: provides command interface to the interpreter
• Tk: Toolkit
• GUI (Graphical User Interface) toolkit
• enables fast, non-verbose GUI prototyping
• creates windows, icons, menus, pointers
• Tk interpreter: parses Tcl and Tk commands/scripts
Page 3
About Tcl/Tk
• The two shells that exist for Tcl/Tk
scripts are :
• Tclsh : Tcl Shell
• Command Line only shell that
allows Tcl commands to be
executed.
• Wish: Windowing Shell
• Displays and manages Tk GUI
components
• Also executes Tcl commands
Page 4
To install Tcl/Tk
• From the N2X Packets and Protocols CD:
• launch from the top-level directory:
TclTk-{version}_for_N2X.exe
where {version} is the Tcl/Tk version, for example,
TclTk-8.3_for_N2X.exe
• From the Tcl Developer Xchange web site:
• http://www.tcl.tk/software/tcltk/
• unpack the self-extracting file
Page 5
To launch the Tcl Shell
• Windows:
• Start menu> (All) Programs> Tcl {version}> Tclsh{version}
• C:\Program Files\Tcl{version}\bin\tclsh{version}.exe
• DOS shell: enter tclsh{version}, for example, tclsh83
• N2X Packets and Protocols GUI:
• Tools menu > Tcl Shell
• UNIX shell:
• [path]/tclsh{version}
Page 6
About Tcl commands
• Sequence of words, separated by white space
• First word is the command name, which may be a
• built-in Tcl/Tk command (proc, set, while, ...)
• Tcl/Tk procedure you define
• Remaining words are command arguments
• Eg:
% puts “Hello World”
% my_own_function 2 3 4 5
Command name Command argument(s)
Page 7
About Tcl commands
• Remaining words can be grouped:
• square braces: [a Tcl command, evaluated to provide an argument]Eg.
% set age [expr 2001 - 1975] % set age 26
• curly braces: {a list, which can be a Tcl command evaluated later}
• quotes: “a string, can include $var and [command] substitutions”
• Long commands continue on next line using “\”
• \ replaced by space in final command
one argument
≡
Page 8
To execute Tcl commands
• Interactively, at the command line
• enter the commands after the % prompt
% puts “Hello World”
Hello World
• In a script
• save the commands in a file with the .TCL extension
• use source to run the script
% source hello.tcl
Hello World
Page 9
To get help
• To list pre-/user-defined commands/procedures:
info commands ?pattern?
% info commands p*
pwd pid proc_mine proc package puts
• Online Help:
• Start menu > (All) Programs > Tcl {version} > Tcl help
• Web:
• http://www.tcl.tk/man/ (manpages)
• see References at end for more
Page 10
To get and print data
• To prompt the user to enter data through STDIN:
gets stdin $variable
% gets stdin address
141.17.9.42
11
• To print data to STDOUT (the Tcl Shell):
puts ?-nonewline? “text_or_variables”
% puts “Connected to: $address”
Connected to: 141.17.9.42
Length of string
Page 11
To set variables
• To assign a variable a value:
set variable value
% set num 42
42
% set decimal 4.2
4.2
% set hex 0xf
0xf
% set string1 hi
hi
% set string2 “hi world”
hi world
% set longstr “This is a \
very long string.”
This is a very long string.
Page 12
To clear and delete variables
• To reset a value:
set variable 0
set variable “”
• To delete a variable:
unset variable
• To list the defined variable names:
info vars
Page 13
To get the time
• In seconds from Tcl Epoch:
clock seconds
% clock seconds
973750148
• In a readable format:
clock format [clock seconds] -format %c
% clock format 973750148 -format %c
Wed Nov 08 22:09:08 2000
• To wait n milliseconds:
after n
% after 1000
Page 14
To add comments
• To add a comment:
• enter # to begin a line (may be preceded by spaces, tabs)
# comment
% # this is a comment
• To add an in-line comment:
• enter the command separator “;” after a command
command ; # comment
% set hPort1 17 ; # this is port 1A
% set hPort2 18 ; # this is port 1B
Page 15
To evaluate expressions
• To evaluate a math or boolean expression:
expr math_or_boolean_expression
% expr 6 + 9
15
% expr 6 == 9
0
% expr 6 == 6
1
• To evaluate an expression in a {list} or “string”:
eval command_in_list_or_string
% set add_later “expr 6 + 9”
expr 6 + 9
% eval $add_later
15
Page 16
To execute conditionally
• When expression true:
if expr body?elseif expr body? ?else body?
• When string matches:
switch ?opt? string {?pattern body??pattern body??default body?
}
• opt may be -exact, -glob, or -regexp
% if { $rx == $tx } {puts “No packet loss”
} elseif { $rx < $tx } {puts “Packets lost”
} else {puts “Packets Rx > Tx”}
% switch -regexp $name {“John” {puts “Hello John”}“S*” {puts “Hello S…….”}“Pete” {puts “Hello Pete”}default {puts “Goodbye”}
}
Page 17
To execute in a loop
• To increment a variable uniformly:
for start test next body
% for {set i 0} {$i < 10} {incr i} {
puts $i
}
• Note: It is incr i not incr $i — incr expects a variable name.
• To work through a list of values:
foreach variable list body
% foreach i {1 5 23} {
puts $i
}
Page 18
To execute in a loop (cont’d)
• To use a while loop:
while test body
% set currPktSize 40
% while {$currPktSize <= 47} {
puts “Current packet: $currPktSize bytes”
set currPktSize [incr currPktSize]
}
• To exit out of a loop early:
break
• To proceed to next loop iteration:
continue
Page 19
To catch errors
• When a fatal error occurs, Tcl shell terminates
• Launch the Tcl shell through DOS to be able to scroll back through
the script output prior to the error
• Or, to handle the error gracefully in scripts:
catch command return_value
set error [catch {open imix.txt} fileHandle]
if {$error} {
puts "Could not open file."
} else {
puts ”File opened, handle = $fileHandle"
}
• if $error = 1, command generated error (0 = success)
Page 20
To manage lists
• A list is a series of items, incrementally indexed
• To create a list:
set list {item1 item2 … }
• To extract a list item (where index = 0 to end):
lindex $list index
% set list {one two {three four} five}
% lindex $list 0
one
% lindex $list 2
three four
% lindex [lindex $list 2] 1
four
Page 21
To manage lists (cont’d)
Command … Use …
llength $list Returns number of items in listlappend list ?item item …? Adds items to the end of a listlinsert $list index ?item item …? Returns list with items before indexlist ?item item …? Returns list of itemslrange $list first_index last_index Returns range of itemslreplace $list first_ind last_ind item Returns list with the range of items
replaced by single itemlsearch $list pattern Index of first occurrencelsort $list Sorts items in a list (by option)join $list ?string? Glues list items togethersplit string {} Returns chars in string
Page 22
To manage arrays
• An array is a like a list but can be indexed using names
• To define array items (one by one, all at once):
set array(index) value
array set array (index1 value1 index2 value2 … )
• To extract an array item, array indexes, values:
$array(index)
array names array
parray array
% array set minlength {ip 40 tcp 64 udp 48}
% parray minlength
minlength(ip) = 40
minlength(tcp) = 64
minlength(udp) = 48
Page 23
To manage strings
• A string is series of ASCII characters
• To define a string or prompt the user for one:
set string {string of characters}
gets stdin $string
• To get the string length, one char, range of chars:
string length $string
string index $string char_index
string range $string first_index last_index
% set address 141.1.2.3
141.1.2.3
% string length $address
9
% set network [string range $address 0 2]
141
Page 24
To manage strings (cont’d)
Command … Returns …
string compare $s1 $s2 -1, 0, or 1, depending on whethers1 is lexicographically <, =, > s2
string equal $s1 $s2 1 if s1 and s2 are equal, 0 if notstring first char $s Index to first occurrence of charstring last char $s Index to last occurrence of charstring match pattern $s 1 if pattern found in s, 0 if notstring tolower $s String in lower casestring toupper $s String in upper casestring trim $s Trims leading, trailing spacesformat $s ?$arg $arg? Formats a string (sprintf)
Page 25
To read from / write to files
• To open a file, get single lines, read the whole file:
set file_handle [open filename]
gets $file_handle line
read $file_handle $file_size_in_chars
• To open a file to write to it:
set file_handle [open filename w]
puts $file_handle $line
% set file_han [open imix.txt]
file136640
% while { [gets $file_han line] >= 0} {
puts $line }
imix.txt
file_han
Page 26
To execute O/S commands
• To execute a DOS command:
command arg1 arg2 …
• To run an application program:
exec program arg1 …
% dir *.txt
Directory of c:\temp
10/14/00 02:00p 19 imix.txt
% exec {C:\WINNT\SYSTEM32\notepad.exe} imix.txt
Page 27
To define procedures
• To define a procedure:
proc name { ? arg1 arg2 … ? } {
? commands ?
? return value ?
}
% proc add {x y} {return [expr $x + $y]}
• To call a procedure:
name ? arg1 arg2 … ?
% add 6 9
15
Page 28
To define procedures (cont’d)
• To define an optional input argument with a default:
proc name { arg1 {arg2 default} } {body}
% proc rate {x {unit “%”}} {puts “$x $unit”}
% rate 100
100 %
% rate 2.4 Gb/s
2.4 Gb/s
• To pass a variable number of arguments:
proc name { args } {body}
% proc printall {args} {
foreach value $args {puts $value}
}
Page 29
To give variables global scope
• Variables defined in the main scope (ie. the top-level script) are
local, not recognized inside procedures
• Variables defined inside a procedure are also local,
not recognized in the main scope
• To use a variable globally:
global var
% proc add_to_base {x} {
global base
return [expr $base + $x] }
% set base 40
% add_to_base 2
42
Page 30
To define paths to Tcl libraries
• To add a path to a Tcl file or package:
auto_mkindex directory file(s)
pkg_mkIndex directory file(s)
% auto_mkindex . *.tcl
% pkg_mkIndex "c:/Program Files/Tcl/lib" *.tcl
• creates a pkgIndex.tcl in that directory to list the file(s) defining
Tcl commands and procedures
• To load the code in a Tcl file or package:
source file
package require file
% package require AgtClient
0.1
Page 31
Adding Tk widgets to your Tcl script
• What is a widget ?
• It's simply a component of your
GUI.
Buttons, menu bars, boxes, these
are all widgets.
• Widgets are created in the wish
shell.
• Widgets are not one line commands.
You have to first tell wish what you
want the widget to look like and do,
and then you have to tell it to put it
on the screen.
widget
Page 32
Adding widgets to your Tcl script
• The syntax for the first part is:
widget_type widget_name option1 option2…
• Eg. : If we create a button directly from the wish
shell :
wish
% button .firstWidget -text "Hello World!”
The line above will create
a button called .firstWidget
Page 33
Adding widgets to your Tcl script
• You may also notice that nothing in your wish window changed.
That's because you have to use something called the Packer
Geometry Manager.
• pack .firstWidget
The pack command places the widget in the wish window.
Page 34
Adding widgets to your Tcl script
• Some common widgets used are :
• button
• checkbutton
• radiobutton
• menubutton
• menu
• canvas
• label
Page 35
Adding widgets to your Tcl script
• entry
• message
• listbox
• text
• scrollbar
• scale
• frame
Page 36
Reference: Tcl Commands (1)
Command … Use …
puts ?-nonewline? “text” prints text and variable datagets stdin $variable gets keyboard data from userset variable value assigns a variable a valueexpr math_or_boolean_expr evaluates a math/boolean expreval command evaluates an expr in a list or stringif expr body ?elseif expr body? : ?else body?
executes conditionally if numeric or
string expression is true
switch ?opt? string { ?pattern body? : ?default body? }
executes conditionally on string or
regular expression match
Page 37
Reference: Tcl Commands (2)
Command … Use …
for start test next body executes continuously, while
incrementing a variable uniformly foreach var list body executes continuously on each
item in a list while test body executes continuously until
condition met catch command return catches a command error set list {item1 item2 … } defines the items in a list lindex $list index extracts an item from a list
llength $list returns # of items in a list
Page 38
Command … Use …
set array(index) valuearray set array (index1 value1 index2 value2 … )$array(index)array names arrayparray array
defines arrays of values indexed
using names
set s {string}string length $sstring index $s indexstring range $s first laststring compare $s1 $s2string equal $s1 $s2format $s ?$arg1 $arg2 …?
defines, checks, and formats
strings
exec program arg1 … runs an application program
Reference: Tcl Commands (3)
Page 39
Reference: Tcl Commands (4)
Command … Use …
set handle [open file ?w?] opens a file (w to write to it) gets $handle line reads lines from a file
puts $handle $line writes lines to a file
proc name {?arg1 arg2?}{ ? commands ? ? return value ? }
defines a modular, re-usable
procedure
name ?arg1 arg2? calls a previously defined
procedure
auto_mkindex dir files pkg_mkIndex dir files
add path to Tcl file/package
source file package require file
loads code in file/package
Page 40
Reference: Special Characters
Character … Use to …
# insert a comment$ replace with a variable’s value[ ] replace with an evaluated commandtab, space separate words (arguments for a command)return separate words inside { }; separate commands in same line\ continue a command on next line\c escape a special character (c){ } denote items in a list“ “ denote items in a string
Page 41
Reference: Arithmetic Operators
Operator … Use to …
+ add - subtract * multiply / divide % get the remainder < > <= >= compare values to yield Boolean true/false == != check equality to yield Boolean true/false & | bitwise AND, OR && || logical AND, OR “ “ denote items in a string
Page 42
Reference: Regular Expressions
Operator … Use to match …
. any character^ beginning of string$ end of string[abc] any character in square brackets[^abc] any character not in square brackets[a-z] range of characters[^a-z] characters not in rangere1|re2 regular expression 1 or 2re* zero or more occurrences of rere+ one or more occurrences of rere? one or one occurrence of re
Page 43
References
• [Intro] Tcl and the Tk Toolkit, John K. Ousterhout, Addison-Wesley,
1994.
• [Reference] Practical Programming in Tcl and Tk, Brent B. Welch,
Prentice Hall, 1997.
• Exploring Expect, Don Libes, O’Reilly, 1994.
• Tcl/Tk software: http://www.tcl.tk/software/tcltk/
• Tcl/Tk manpages: http://www.tcl.tk/man/
• Tcl/Tk how to guides: http://www.tcl.tk/doc/howto/
Page 44
Resources
• TclPro: Tcl development tools
• code checker, graphical debugger, Tcl application packager
• http://www.tcl.tk/software/tclpro/
• Edit +: syntax highlighter/checker
• costs US $30, free 30-day trial available on web
• http://editplus.com
• an EditPlus syntax file for the N2X Packets and Protocol Tcl API is installed with the software:
C:\Program Files\Agilent\N2X\RouterTester900\{version}\etc\editplus\RouterTesterTclTk.stx