7
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby NetAddr Package

Posted at

Rubyには標準でIPAddrというクラスがあるが、これでIPアドレスを柔軟に扱うことはなかなか難しい。

そんな中色々探していたら、NetAddrというパッケージがあって、これが便利そうなので紹介しておく。
https://rubygems.org/gems/netaddr/versions/1.5.0
http://www.rubydoc.info/gems/netaddr/1.5.0/NetAddr

ただ、Webにはそれほどサンプルがない。。個人的には超ステキなパッケージだと思うが、NWエンジニアがRubyを触ることは世界的にもまだ少ないからなのか・・・?

gem install netaddrで普通にインストール

CIDRからGatewayアドレス(末尾アドレス)を算出するサンプルプログラム

require 'netaddr'

netaddr1 = NetAddr::CIDR.create('192.168.1.0/24')

# broadcastアドレスを算出
bc_address = netaddr1.last

# 数値化して1引く
gateway_int = NetAddr::CIDR.create(bc_address).to_i - 1
# その数値をアドレス表記に戻す
gateway = NetAddr.i_to_ip(gateway_int)

# /24部分だけを抽出
netmask = netaddr1.netmask

p bc_address
# => "192.168.1.255"

p gateway
# "192.168.1.254"

puts gateway + netmask
# => 192.168.1.254/24

この他にもARPA形式出力やrange指定、IPv6対応など、色々便利なメソッドがある。
使えそうなメソッドのメモ書きをしておく。

require 'netaddr'

netaddr1 = NetAddr::CIDR.create('192.168.1.0/24')
netaddr2 = NetAddr::CIDR.create('192.168.1.1 255.255.0.0')
netaddr3 = NetAddr::CIDR.create('192.168.1.1 255.255.255.0')
netaddr4 = NetAddr::CIDR.create('224.0.0.1')

p netaddr1.bits
# => 24

p netaddr2.broadcast
# => "192.168.255.255"

p netaddr3.netmask
# => "/24"

p netaddr3.network
# => "192.168.1.0"

p netaddr3.subnet
# => ["192.168.1.0/25", "192.168.1.128/25"]

p netaddr1.arpa
# => "1.168.192.in-addr.arpa."

p netaddr1.cmp('192.168.0.0/16')
# => -1

p netaddr2.desc
# => "192.168.0.0/16"


#p netaddr1.enumerate
# => ["192.168.1.0", ..... , "192.168.1.255"]とダーッと出る

p netaddr2.ip
# => "192.168.1.1"

p netaddr2.last
# => "192.168.255.255"

p netaddr4.multicast_mac
# => "01-00-5e-00-00-01"

p netaddr1.next_ip
# => "192.168.2.0"

p netaddr1.next_subnet
# => "192.168.2.0/24"

p netaddr3.to_i
# => 3232235776

p NetAddr.i_to_ip(3232235776)
# => "192.168.1.0"

p netaddr1.to_s
# => "192.168.1.0/24"

p netaddr1.wildcard_mask
# => "255.255.255.0"

p netaddr1.hostmask_ext
# => "0.0.0.255"

p netaddr1.netmask_ext
# => "255.255.255.0"
7
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?