ip-int.rb

Heads up: This description was created by AI and might not be 100% accurate.

This Ruby code snippet demonstrates converting an IP address string (e.g., “192.168.1.10”) into its integer representation, then extracting its individual octets (first, second, third, and fourth) and finally converting it back to an IP address string. It utilizes bitwise operations and string manipulation for this conversion.

Ruby code snippet

ip_str = "192.168.1.10"
#=> "192.168.1.10"

# 文字列 → Integer
#=> nil
ip_int = ip_str.split('.').map(&:to_i).pack('C*').unpack1('N')
#=> 3232235786

first  = (ip_int >> 24) & 0xFF
#=> 192
second = (ip_int >> 16) & 0xFF
#=> 168
third  = (ip_int >> 8)  & 0xFF
#=> 1
fourth = ip_int & 0xFF
#=> 10

ip_back = [ip_int].pack('N').unpack('C4').join('.')
#=> "192.168.1.10"

Executed with Ruby 3.4.8.