Ip Int.rb

This content was produced by an LLM and could include errors.

This script demonstrates converting an IPv4 address string into a 32-bit integer using packing and unpacking. It then extracts and reconstructs the individual octets using bitwise shifting.

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"

Ruby 4.0.3