Rails 如何在计算 ip 范围之前验证子网掩码
Rails how to validate subnet mask before ip range calculation
我正在使用 netaddr gem 来验证网络 IP 范围。但是我找不到验证给定子网掩码有效的方式?
def valid_ip_range(ip, gateway, subnet_mask)
ip_range = NetAddr::CIDR.create("#{gateway} #{subnet_mask}")
valid_ip_range = NetAddr.range(ip_range.first, ip_range.last)
valid_ip_range.include?(ip_ip)
end
对于有效的子网掩码
ip_range = NetAddr::CIDR.create('192.168.1.1 255.255.255.0')
=> #<NetAddr::CIDRv4:0x0000000b334720 @address_len=32, @all_f=4294967295, @hostmask=255, @ip=3232235777, @netmask=4294967040, @network=3232235776, @tag={}, @version=4, @wildcard_mask=4294967040>
对于无效的子网掩码,出现以下错误
ip_range = NetAddr::CIDR.create('192.168.1.1 255.128.128.0')
ip_range = NetAddr::CIDR.create('192.168.1.1 1.1.1.1')
=> NetAddr::ValidationError: 1.1.1.1 contains '1' bits within the host portion of the netmask.
from /ruby-2.1.1@customerservice-mar/gems/netaddr-1.5.1/lib/validation_shortcuts.rb:182:in `block in validate_netmask_str'
require 'ipaddr'
net1 = IPAddr.new("192.168.2.0/24")
net2 = IPAddr.new("192.168.2.100")
net3 = IPAddr.new("192.168.3.0")
p net1.include?(net2) #=> true
p net1.include?(net3) #=> false
我正在使用 netaddr gem 来验证网络 IP 范围。但是我找不到验证给定子网掩码有效的方式?
def valid_ip_range(ip, gateway, subnet_mask)
ip_range = NetAddr::CIDR.create("#{gateway} #{subnet_mask}")
valid_ip_range = NetAddr.range(ip_range.first, ip_range.last)
valid_ip_range.include?(ip_ip)
end
对于有效的子网掩码
ip_range = NetAddr::CIDR.create('192.168.1.1 255.255.255.0')
=> #<NetAddr::CIDRv4:0x0000000b334720 @address_len=32, @all_f=4294967295, @hostmask=255, @ip=3232235777, @netmask=4294967040, @network=3232235776, @tag={}, @version=4, @wildcard_mask=4294967040>
对于无效的子网掩码,出现以下错误
ip_range = NetAddr::CIDR.create('192.168.1.1 255.128.128.0')
ip_range = NetAddr::CIDR.create('192.168.1.1 1.1.1.1')
=> NetAddr::ValidationError: 1.1.1.1 contains '1' bits within the host portion of the netmask.
from /ruby-2.1.1@customerservice-mar/gems/netaddr-1.5.1/lib/validation_shortcuts.rb:182:in `block in validate_netmask_str'
require 'ipaddr'
net1 = IPAddr.new("192.168.2.0/24")
net2 = IPAddr.new("192.168.2.100")
net3 = IPAddr.new("192.168.3.0")
p net1.include?(net2) #=> true
p net1.include?(net3) #=> false