Skip to content

Add IPAddr.netmask class method - #143

Closed
datibbaw wants to merge 1 commit into
ruby:masterfrom
datibbaw:add-netmask-class-method
Closed

datibbaw wants to merge 1 commit into
ruby:masterfrom
datibbaw:add-netmask-class-method

Conversation

@datibbaw

Copy link
Copy Markdown
Contributor

Summary

Adds IPAddr.netmask(prefixlen, family = Socket::AF_INET), which returns the netmask string for a prefix length:

IPAddr.netmask(24)                    #=> "255.255.255.0"
IPAddr.netmask(64, Socket::AF_INET6)  #=> "ffff:ffff:ffff:ffff:0000:0000:0000:0000"

Closes #83. Supersedes #117, which appears to be inactive. This version follows the review feedback given there:

Details

  • prefixlen must be an Integer; otherwise InvalidPrefixError is raised. Without this check, IPAddr#mask would accept "24" and "255.255.255.0", raise NoMethodError for nil, and return a non-contiguous mask for 24.5.
  • Range checks (InvalidPrefixError) and family checks (AddressFamilyError) are left to IPAddr#mask and IPAddr.new.
  • family defaults to Socket::AF_INET.

Tests

Added test_class_netmask, covering IPv4/IPv6 boundary prefixes, the default family, non-Integer and out-of-range prefixes, and AF_UNSPEC.

Return the netmask string for a given prefix length and address
family, defaulting to IPv4:

    IPAddr.netmask(24)                    #=> "255.255.255.0"
    IPAddr.netmask(64, Socket::AF_INET6)  #=> "ffff:ffff:ffff:ffff:0000:0000:0000:0000"

The prefix length must be an Integer; range and family validation are
delegated to IPAddr.new and IPAddr#mask.

Closes ruby#83.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@datibbaw
datibbaw requested a review from knu as a code owner November 19, 2026 13:08
@taketo1113

Copy link
Copy Markdown
Collaborator

@datibbaw Thank you for your contribution.

Since there has been an update to #117, I will close this pull request.

@taketo1113 taketo1113 closed this Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enhancement: add constants for IPv4 and IPv6 subnet masks

2 participants