Last active
August 29, 2015 14:11
-
-
Save BrentonEarl/4f61a3c6e4a8c1a87ce5 to your computer and use it in GitHub Desktop.
Ruby class that makes use of ruby 2.1's new Socket.getifaddrs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require 'netaddr' # this is a gem | |
class Address | |
# Pull the ip address from the local machine | |
def initialize | |
@info = Socket.getifaddrs.find do |ifaddr| | |
(ifaddr.flags & Socket::IFF_BROADCAST).nonzero? && | |
ifaddr.addr.afamily == Socket::AF_INET | |
end | |
end | |
# Return ip address as string | |
def ip_to_s | |
@info.addr.ip_address | |
end | |
# Return netmask as a string | |
def mask_to_s | |
@info.netmask.ip_address | |
end | |
def start_address_to_s | |
@info.addr.ip_address.split('.')[0..2].join('.') + ".0".to_s | |
end | |
# Return Broadcast address as a string | |
def broadcast_to_s | |
@info.broadaddr.ip_address | |
end | |
# Determine CIDR value based netmask | |
def cidr_to_s | |
NetAddr::CIDR.create('0.0.0.0/'+"#{mask_to_s}").netmask | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment