cli icon indicating copy to clipboard operation
cli copied to clipboard

IP calculator

Open UmanShahzad opened this issue 2 years ago • 0 comments

Here's some new subcommand ideas:

  • ipinfo calc <expr>
  • ipinfo ip2n (ip to number)
  • ipinfo n2ip (number to ip - v4 if it fits, v6 otherwise, with an option to force v6)
  • ipinfo n2ip6 (forced ipv6 version of n2ip).

The <expr> for the calc subcmd can be an infix mathematical expression that supports (, ), ^, *, /, +, - - PEMDAS - integers, and IP addresses.

For example:

$ ipinfo calc '2*(1.1.1.0 + 2)'
$ ipinfo calc '::/2'
$ ipinfo calc '2*2' # even this can work just fine

We just need to convert the IPs to numbers, convert the infix to postfix, and then execute a simple stack-based algorithm to calculate the resulting postfix expression.

One confusion about it is that the / and - operators are used in IP-related notations like CIDRs and Ranges already, so that could look a little weird. It'd be a problem if we wanted to support mathematical operations on cidrs/ranges only though I suppose.

I think there's a lot more interesting operations to be done with IPs than the basic math ops above.

cc @coderholic

UmanShahzad avatar Jul 08 '22 01:07 UmanShahzad