From f90b36f2da80070411131af985c2af9f236a1685 Mon Sep 17 00:00:00 2001 From: Mike Mackintosh Date: Mon, 26 Jan 2015 16:21:55 -0500 Subject: added #ntoa unint32 -> ip and tests --- lib/ipaddress.rb | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'lib') diff --git a/lib/ipaddress.rb b/lib/ipaddress.rb index e2161e1..4033c3a 100644 --- a/lib/ipaddress.rb +++ b/lib/ipaddress.rb @@ -26,6 +26,7 @@ module IPAddress # Parse the argument string to create a new # IPv4, IPv6 or Mapped IP object # + # ip = IPAddress.parse 167837953 # 10.1.1.1 # ip = IPAddress.parse "172.16.10.1/24" # ip6 = IPAddress.parse "2001:db8::8:800:200c:417a/64" # ip_mapped = IPAddress.parse "::ffff:172.16.10.1/128" @@ -41,6 +42,12 @@ module IPAddress # #=> IPAddress::IPv6::Mapped # def IPAddress::parse(str) + + # Check if an int was passed + if str.kind_of? Integer + return IPAddress::IPv4.new(ntoa(str)) + end + case str when /:.+\./ IPAddress::IPv6::Mapped.new(str) @@ -53,6 +60,24 @@ module IPAddress end end + # + # Converts a unit32 to IPv4 + # + # IPAddress::ntoa(167837953) + # #-> "10.1.1.1" + # + def self.ntoa(uint) + unless(uint.is_a? Numeric and uint <= 0xffffffff) + raise(::ArgumentError, "not a long integer: #{uint.inspect}") + end + ret = [] + 4.times do + ret.unshift(uint & 0xff) + uint >>= 8 + end + ret.join('.') + end + # # True if the object is an IPv4 address # -- cgit v1.2.1