Skip to content

Enhancement: add constants for IPv4 and IPv6 subnet masks #83

Description

@MatzFan

Rationale: This SO question demonstrates there is at least some need to manipulate netmasks into CIDR integers. The accepted answer contains a bug which can be easily eliminated by hard coding the 2 sets of netmasks into the IPAddr class - see my alternative answer.

Proposed solution: Define IPAddr::IPV4_SUBNET_MASKS and IPAddr::IPV6_SUBNET_MASKS as follows:

class IPAddr
  IPV4_SUBNET_MASKS = (0..32).map { |n| IPAddr.new("0.0.0.0/#{n}").netmask }
  IPV6_SUBNET_MASKS = (0..128).map { |n| IPAddr.new("0::/#{n}").netmask }
end

# Now a user can do the following to get a subnet mask from a CIDR integer:
IPAddr::IPV4_SUBNET_MASKS[24]
# => "255.255.255.0"

IPAddr::IPV6_SUBNET_MASKS[64]
# => "ffff:ffff:ffff:ffff:0000:0000:0000:0000"

Optional: Add a predicate to check if an instance of IPAddr is a netmask:

class IPAddr
  def netmask?
    if ipv4?
      IPV4_SUBNET_MASKS.include? to_s
    else
      IPV6_SUBNET_MASKS.include? to_s
    end
  end
end

ipaddr1 = IPAddr.new '255.254.255.0'
ipaddr1.netmask? # => false

ipaddr2 = IPAddr.new '255.255.255.0/24'
ipaddr2.netmask? # => true

ipaddr3 = IPAddr.new '255.255.255.0'
ipaddr3.netmask? # => true

# And so on for IPv6 addresses

Activity

  1. taketo1113 commented on Aug 11, 2026

    @taketo1113
    Collaborator

    @MatzFan Since IPAddr#prefix and IPAddr#netmask are available, you can convert a netmask to a prefix length and a prefix length to a netmask without defining the proposed constants, as follows:

    # IPv4
    addr = IPAddr.new("0.0.0.0")
    #=> #<IPAddr: IPv4:0.0.0.0/255.255.255.255>
    
    # netmask -> prefix
    addr.mask("255.255.0.0").prefix
    #=> 16
    
    # prefix -> netmask
    addr.mask(16).netmask
    #=> "255.255.0.0"
    
    
    # IPv6
    addr = IPAddr.new("::")
    #=> #<IPAddr: IPv6:0000:0000:0000:0000:0000:0000:0000:0000/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff>
    
    # netmask -> prefix
    addr.mask("ffff:ffff:ffff:0000:0000:0000:0000:0000").prefix
    #=> 48
    
    # prefix -> netmask
    addr.mask(48).netmask
    #=> "ffff:ffff:ffff:0000:0000:0000:0000:0000"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions