Rpj Rpj - 3 months ago 13
Ruby Question

How to increment the last octet in an IP address

How to write a ruby helper function which will increment from

222.164.153.58 to 222.164.153.59
or increment the 3rd octet properly if it hits the max on the 4th octet.

Answer

Use IPAddr#succ.

require "ipaddr"

addr = IPAddr.new "222.164.153.58"
addr.succ
#=> #<IPAddr: IPv4:222.164.153.59/255.255.255.255>

addr = IPAddr.new "192.168.2.255"
addr.succ
#=> #<IPAddr: IPv4:192.168.3.0/255.255.255.255>