ruby / ruby/ipaddr

Enhancement: add constants for IPv4 and IPv6 subnet masks

Open
#83 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Ruby
Stars
82
Forks
42
Avg merge
2h 24m
Merged PRs (30d)
3

Description

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in the IPAddr class and inspect the existing IPv4, IPv6, and netmask handling. Add coverage for the proposed subnet-mask constants and, if the optional predicate is included, its IPv4 and IPv6 cases; done means CIDR indexes return the documented masks and non-contiguous masks are rejected.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
networking
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
64/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.