Browse Source

ipcalc: bignum calculation

master
Maxim Likhachev 4 years ago
parent
commit
2149f28e98
  1. 19
      scripts/ipcalc

19
scripts/ipcalc

@ -30,6 +30,7 @@ @@ -30,6 +30,7 @@
#
# ------------------------------------------------------------------------------
package require math::bignum
# Convert integer to binary
proc int2bin {int} {
@ -52,6 +53,18 @@ proc decimal2binary {decimal_ip} { @@ -52,6 +53,18 @@ proc decimal2binary {decimal_ip} {
return [join [lmap x [split $decimal_ip {.}] {int2bin $x}] {.}]
}
# Bignum calculation
proc = {expr x y} {
set big_x [::math::bignum::fromstr $x 2]
pad_address [::math::bignum::tostr [::math::bignum::$expr $big_x $y] 2]
}
# Add leader zeroes to binary IP address
proc pad_address {binary_ip} {
format %032s $binary_ip
}
# Normalize binary form of IP address
# E.g.:
# 11111111.11111111.11111111.00000000 => 11111111111111111111111100000000
@ -182,7 +195,8 @@ proc host_broadcast {ip netmask} { @@ -182,7 +195,8 @@ proc host_broadcast {ip netmask} {
# 190.0.15.254 10111110.00000000.00001111.11111110
proc host_max {ip netmask} {
set binary_broadcast [lindex [host_broadcast $ip $netmask] 1]
set binary_max_host [format_binary_ip [expr {[normalize_binary_ip [lindex [host_broadcast $ip $netmask] 1]]-1}]]
set normalized_binary_ip [normalize_binary_ip [lindex [host_broadcast $ip $netmask] 1]]
set binary_max_host [format_binary_ip [pad_address [= sub $normalized_binary_ip 1]]]
set max_host [binary2decimal $binary_max_host]
return [list $max_host $binary_max_host]
@ -199,7 +213,8 @@ proc host_max {ip netmask} { @@ -199,7 +213,8 @@ proc host_max {ip netmask} {
proc host_min {ip netmask} {
set network [lindex [network $ip $netmask] 1]
set min_host [expr {[normalize_binary_ip $network]+1}]
set normalized_binary_ip [normalize_binary_ip $network]
set min_host [= add $normalized_binary_ip 1]
set binary_min_host [format_binary_ip $min_host]
set decimal_min_host [binary2decimal $min_host]

Loading…
Cancel
Save