2012-06-29 05:18:28 +00:00
|
|
|
# -*- coding: binary -*-
|
2005-10-27 04:14:02 +00:00
|
|
|
require 'rex/socket'
|
|
|
|
|
|
|
|
module Rex
|
|
|
|
module Socket
|
|
|
|
|
|
|
|
###
|
|
|
|
#
|
|
|
|
# This class provides an interface to enumerating a subnet with a supplied
|
|
|
|
# netmask.
|
|
|
|
#
|
|
|
|
###
|
|
|
|
class SubnetWalker
|
|
|
|
|
2005-11-15 05:22:13 +00:00
|
|
|
#
|
|
|
|
# Initializes a subnet walker instance using the supplied subnet
|
|
|
|
# information.
|
|
|
|
#
|
2005-10-27 04:14:02 +00:00
|
|
|
def initialize(subnet, netmask)
|
|
|
|
self.subnet = Socket.resolv_to_dotted(subnet)
|
|
|
|
self.netmask = Socket.resolv_to_dotted(netmask)
|
|
|
|
|
|
|
|
reset
|
|
|
|
end
|
|
|
|
|
|
|
|
#
|
|
|
|
# Resets the subnet walker back to its original state.
|
|
|
|
#
|
|
|
|
def reset
|
|
|
|
self.curr_ip = self.subnet.split('.')
|
2009-07-09 22:39:30 +00:00
|
|
|
self.num_ips = (1 << (32 - Socket.net2bitmask(self.netmask).to_i))
|
2005-10-27 04:14:02 +00:00
|
|
|
self.curr_ip_idx = 0
|
|
|
|
end
|
|
|
|
|
|
|
|
#
|
|
|
|
# Returns the next IP address.
|
|
|
|
#
|
|
|
|
def next_ip
|
2009-07-09 22:39:30 +00:00
|
|
|
if (curr_ip_idx >= num_ips)
|
2005-10-27 04:14:02 +00:00
|
|
|
return nil
|
|
|
|
end
|
|
|
|
|
|
|
|
if (curr_ip_idx > 0)
|
|
|
|
self.curr_ip[3] = (curr_ip[3].to_i + 1) % 256
|
|
|
|
self.curr_ip[2] = (curr_ip[2].to_i + 1) % 256 if (curr_ip[3] == 0)
|
|
|
|
self.curr_ip[1] = (curr_ip[1].to_i + 1) % 256 if (curr_ip[2] == 0)
|
|
|
|
self.curr_ip[0] = (curr_ip[0].to_i + 1) % 256 if (curr_ip[1] == 0)
|
|
|
|
end
|
|
|
|
|
|
|
|
self.curr_ip_idx += 1
|
2013-03-08 00:16:57 +00:00
|
|
|
|
2005-10-27 04:14:02 +00:00
|
|
|
self.curr_ip.join('.')
|
|
|
|
end
|
|
|
|
|
2005-11-15 05:22:13 +00:00
|
|
|
#
|
|
|
|
# The subnet that is being enumerated.
|
|
|
|
#
|
|
|
|
attr_reader :subnet
|
|
|
|
#
|
|
|
|
# The netmask of the subnet.
|
|
|
|
#
|
|
|
|
attr_reader :netmask
|
|
|
|
#
|
|
|
|
# The total number of IPs within the subnet.
|
|
|
|
#
|
|
|
|
attr_reader :num_ips
|
2005-10-27 04:14:02 +00:00
|
|
|
|
|
|
|
protected
|
|
|
|
|
2005-11-15 05:22:13 +00:00
|
|
|
attr_writer :subnet, :netmask, :num_ips # :nodoc:
|
|
|
|
attr_accessor :curr_ip, :curr_ip_idx # :nodoc:
|
2005-10-27 04:14:02 +00:00
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
2009-07-09 22:39:30 +00:00
|
|
|
end
|