mgl
mgl

Reputation: 41

Removing the last IP Address Octet in Ruby

In Ruby, I'm wanting to take my local IP address and convert it into my network id (e.g. 192.168.1.1 to 192.168.1.0)

require "socket"
local_ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}

This will give me my local ip, but how can I remove the last octet up to the dot(.)?

Upvotes: 4

Views: 2322

Answers (1)

YOU
YOU

Reputation: 123881

quick and dirty way would be something like

"192.168.1.1".rpartition(".")[0]
=> "192.168.1"

but if you know subnet mask or if you are running on subnets other than 24 bits (255.255.255.0), you should use IPAddr module, since network of those can be differ based on subnets.

> require 'IPAddr'
=> true
>  
> IPAddr.new("64.233.187.99/24").to_s
=> "64.233.187.0"

> IPAddr.new("64.233.187.99/20").to_s
=> "64.233.176.0"

refs:

Upvotes: 5

Related Questions