Ruby: Get Local Ip (Nix)

Ruby: get local IP (nix)

A server typically has more than one interface, at least one private and one public.

Since all the answers here deal with this simple scenario, a cleaner way is to ask Socket for the current ip_address_list() as in:

require 'socket'

def my_first_private_ipv4
Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
end

def my_first_public_ipv4
Socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}
end

Both returns an Addrinfo object, so if you need a string you can use the ip_address() method, as in:

ip= my_first_public_ipv4.ip_address unless my_first_public_ipv4.nil?

You can easily work out the more suitable solution to your case changing Addrinfo methods used to filter the required interface address.

Getting the Hostname or IP in Ruby on Rails

From coderrr.wordpress.com:

require 'socket'

def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily

UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end

# irb:0> local_ip
# => "192.168.0.127"

Get own IP address

Try:

require 'socket'
ip=Socket.ip_address_list.detect{|intf| intf.ipv4_private?}
ip.ip_address if ip

Mac addresses of all devices on LAN in Ruby?

Substitute your actual IP range for the X's

ping -c 2 x.x.x.255

And then parse the results of an

arp -a

Ruby - See if a port is open

Something like the following might work:

require 'socket'
require 'timeout'

def is_port_open?(ip, port)
begin
Timeout::timeout(1) do
begin
s = TCPSocket.new(ip, port)
s.close
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false
end
end
rescue Timeout::Error
end

return false
end

How to get Host name in Rails 3?

You have several options:

  • call system's hostname command (assuming it's *nix): `hostname`
  • use the socket gem:

    require 'socket'

    Socket.gethostname

  • in case you just want to know the current domain the request visits: request.domain

Update

From the request object, we can fetch both the host and the port, please check out these methods:

  • request.protocol
  • request.host
  • request.port

You could build the full url from these methods.

From my personal experience, for most projects you might have a fixed domain for each environment, and usually configure that in a yaml file or so (for example, to send email and use urls with domain name in the email body, we usually read the config and set options for url helper). So I usually just read the current environment's urls configuration and use them from the code.



Related Topics



Leave a reply



Submit