I have a ip addr string as “192.168.000.000”, I use succ! method to get
the next ip addr string. It works for the first 255 times but when ip
reachs “192.168.000.255”, the succ! returns “192.168.000.256” but what I
want is “192.168.001.000”. Would anyone kindly help to tell me how to
do?
I have a ip addr string as “192.168.000.000”, I use succ! method to get
the next ip addr string. It works for the first 255 times but when ip
reachs “192.168.000.255”, the succ! returns “192.168.000.256” but what I
want is “192.168.001.000”. Would anyone kindly help to tell me how to
do?
Thanks in advance.
Instead of strings, use the IPAddr core class to represent IP addresses.
While it doesn’t have a built in method for determining the next IP
address, you can add the functionality like so:
$ irb
irb(main):001:0> require ‘ipaddr’
=> true
irb(main):002:0> class IPAddr
irb(main):003:1> def succ!
irb(main):004:2> @addr += 1
irb(main):005:2> self
irb(main):006:2> end
irb(main):007:1> end
=> nil
irb(main):008:0> a = IPAddr.new(‘192.168.0.255’)
=> #<IPAddr: IPv4:192.168.0.255/255.255.255.255>
irb(main):009:0> a.succ!
=> #<IPAddr: IPv4:192.168.1.0/255.255.255.255>
irb(main):010:0>