LoginSignup
9
9

More than 5 years have passed since last update.

【Ruby】対象のIPアドレスがプライベートIPアドレスかどうか確認する

Posted at

IPAddr クラスにそういうメソッドが見当たらなかった。

#!/usr/bin/env ruby

require "ipaddr"

def private_ip?(target)
  IPAddr.new("10.0.0.0/8").include?(target) ||
  IPAddr.new("172.16.0.0/12").include?(target) ||
  IPAddr.new("192.168.0.0/16").include?(target)
end

p private_ip?("8.8.8.8")
p private_ip?("10.10.10.10")
#=> false
#=> true
9
9
1

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
9
9