Updated 2011-10-11 11:07:21 by RLE

Small calculator using Tile only using IPv4 and no tcllib - allows one to type IP/netmask and get the corresponding broadcast/network addresses. 5 minutes' fun project :)
  package require Tk
 
  proc ip2val {str} {
    set rc 0
    foreach v [lrange [split $str .] 0 3] {
         if {[catch {
             set v [expr {($v & 0xff)}]
         }]} {
             set v 0
         }
         set rc [expr {($rc << 8) + $v}]
    }
    return $rc
  }
 
  proc val2ip {v} {
    return [format %d.%d.%d.%d \
         [expr {(($v >> 24) & 0xff)}] \
         [expr {(($v >> 16) & 0xff)}] \
         [expr {(($v >>  8) & 0xff)}] \
         [expr  {($v & 0xff)}] \
         ]
  }
 
  proc docalc {args} {
    global ipaddr netmask broadcast netaddr
 
    set ip [ip2val $ipaddr]
    set nm [ip2val $netmask]
    set ::netaddr   [val2ip [expr {($ip & $nm)}]]
    set ::broadcast [val2ip [expr {($ip & $nm) | ($nm ^ 0xffffffff)}]]
  }
 
  set ::ipaddr  ""
  set ::netmask ""
  trace add variable ::ipaddr  write docalc
  trace add variable ::netmask write docalc
  docalc
 
  ttk::label .l0 -anchor e -text "IP Address"
  ttk::label .l1 -anchor e -text "Netmask"
  ttk::label .l2 -anchor e -text "Broadcast"
  ttk::label .l3 -anchor e -text "Network address"
 
  ttk::entry .e0 -textvariable ::ipaddr
  ttk::entry .e1 -textvariable ::netmask
  ttk::entry .e2 -textvariable ::broadcast
  ttk::entry .e3 -textvariable ::netaddr
 
  grid .l0 .e0 -pady 2 -padx 2
  grid .l1 .e1 -pady 2 -padx 2
  grid .l2 .e2 -pady 2 -padx 2
  grid .l3 .e3 -pady 2 -padx 2
 
  wm resizable . 0 0
  wm title . "IP calculator"

 #ttk::setTheme default
  ttk::setTheme winnative

See also A Little CIDR Calculator for a slightly different approach.

HJG What is the advantage of using tile here ? It seems to work just fine without all those "ttk::", and setting a theme just colors the labels in a different shade of gray...