TCL proc to increment the valid IP and IPv6 Address by given number of times

//procIncrIP.exp
#!/usr/bin/tclsh
proc increment_ip {ip no_of_inc} {
puts "Ip address --- $ip"
for {set inc 1} {$inc<=$no_of_inc} {incr inc} {
set ip_list [split $ip "."]
set oct1 [lindex $ip_list 0]
set oct2 [lindex $ip_list 1]
set oct3 [lindex $ip_list 2]
set oct4 [lindex $ip_list 3]
incr oct4
if {$oct4>255} {
set oct4 0
incr oct3
}
if {$oct3>255} {
set oct3 0
incr oct2
}
if {$oct2>255} {
set oct2 0
incr oct1
}
if {$oct1>255} {
incr oct1 -1
puts "cannot increment ip"
exit
}
set ip $oct1.$oct2.$oct3.$oct4
puts "next ip -- $ip"
}
}
//calling the proc
increment_ip 1.1.1.252 10
Output :
[root@QATS tcl]# tclsh procIncrIP.exp
Ip address --- 1.1.1.252
next ip -- 1.1.1.253
next ip -- 1.1.1.254
next ip -- 1.1.1.255
next ip -- 1.1.2.0
next ip -- 1.1.2.1
next ip -- 1.1.2.2
next ip -- 1.1.2.3
next ip -- 1.1.2.4
next ip -- 1.1.2.5
next ip -- 1.1.2.6

 

Program to increment the IPv6 address :  Before moving to the program first we will discuss little about IPv6 Address representation.

IPv6 Address representation :
An IPv6 address is made of 128 bits divided into eight 16-bits blocks. Each block is then converted into 4-digit Hexadecimal numbers separated by colon symbols.

For example, given below is a 128 bit IPv6 address represented in binary format and divided into eight 16-bits blocks:

0010000000000001 0000000000000000 0011001000111000 1101111111100001 0000000001100011 0000000000000000 0000000000000000 1111111011111011
Each block is then converted into Hexadecimal and separated by ‘:’ symbol:

2001:0000:3238:DFE1:0063:0000:0000:FEFB
Even after converting into Hexadecimal format, IPv6 address remains long. 

//procIncrIPv6.exp
proc next_ip {ip} {
   set parts [split $ip :]
   set last_part 0x[lindex $parts end]
   set next [format %x [expr {$last_part + 1}]]
   lset parts end $next
   set next_ipv6 [join $parts ":"]
   puts "$next_ipv6"

}

next_ip fe80:0000:0000:0000:0204:61ff:fe9d:f15f


Output :
fe80:0000:0000:0000:0204:61ff:fe9d:f160

No comments:

Post a Comment