Reputation: 11
i want to convert string to number to use in SCP command. can someone please help?
set ip "192.168.1.2"
scp:root@$ip//etc/dev/
it doesn't replace $ip
with the IP i had set.
how do I convert the IP to number as the scp command is expecting number rather than string.
Thanks
Upvotes: 1
Views: 1867
Reputation: 12561
This is not about converting any string to a number, but rather an IP address. In Tcl most everything is a string, so you just use the expr command for math and it will do the conversion as necessary. Notice how in my implementation below inside expr
I simply refer to [lindex $octets $i]
which is a string derived from splitting the IP address, yet the command still runs as expected.
The below is a naive implementation of what you are really asking for: converting an IP address to a number (integer); you would want to enhance it with various validations (length of the segments array, min/max of each segment, etc.) -- this is why a library as suggested in the other answer may be a better way, not to mention possibly being equipped to handle ipv6 which I simply ignore ;)
Here's an explanation of the implementation in general; please anybody feel free to edit with a better one. A note on my implementation: by reversing the list, I make it trivial to multiply the last octet by 256^0, the next to last octet by 256^1, etc, the power being the lindex.
set ip "192.168.1.2"
set ip_as_int 0
set octets [lreverse [split $ip .]]
for {set i 0} {$i < 4} {incr i} {
set ip_as_int [expr {256 ** $i * [lindex $octets $i] + $ip_as_int}]
}
puts $ip_as_int ;#3232235778
Upvotes: 1
Reputation: 247072
You'll want a library to do that. tcllib has an IP address manipulation module:
package require ip
set ip "192.168.1.2"
set num [ip::toInteger $ip]
puts $num
puts [ip::intToString $num]
-1062731518
192.168.1.2
This looks odd: scp:root@$ip//etc/dev/
Recall that Tcl evaluates commands like command word ...
, and there's no whitespace in that "scp" command, so Tcl will try to find a command named "scp:[email protected]//etc/dev/" -- I bet it can't find one.
Upvotes: 1