Ruby - Platform Independent Way to Determine Ips of All Network Interfaces

Ruby - Platform independent way to determine IPs of all network interfaces?

As of Ruby 2.1, Socket#getifaddrs is available:

001:0> require 'socket'
=> true
002:0> Socket.getifaddrs.map { |i| i.addr.ip_address if i.addr.ipv4? }.compact
=> ["127.0.0.1", "192.168.1.121", "192.168.1.181"]

Platform independent method of getting IP address of primary network interface

Looking at the documentation for Ruby's Socket class, your Python code can be translated almost 1:1 to Ruby:

require "socket"

def get_ip_address
s = Socket.new(Socket::AF_INET, Socket::SOCK_DGRAM)
s.connect(Socket.pack_sockaddr_in(80, "8.8.8.8"))
Socket.unpack_sockaddr_in(s.getsockname)[1]
end

puts "My IP address: #{get_ip_address}"

How can I get the system's IP address(es) AND (their) associated MAC address in Ruby?

You can extract interface names from Socket.getifaddrs elements:

require 'socket'
Socket.getifaddrs.each { |if_addr| puts if_addr.name }

In a similar way you can also get de IP addresses related to the names:

require 'socket'
Socket.getifaddrs.each do |if_addr|
next unless if_addr.addr.ipv4?
puts "#{if_addr.name} => #{if_addr.addr.ip_address.to_s}"
end

And finally more or less the same for the MAC address:

require 'socket'
Socket.getifaddrs.each do |if_addr|
next unless if_addr.addr.pfamily == Socket::PF_LINK
puts "#{if_addr.name} => #{if_addr.addr.getnameinfo}"
end

Note: Some interfaces could not have a MAC address an returns empty arrays

You only have to join it have your hash :)

PHP - Get Gateway/Router IP, UPnP

You could retrieve it using external services such as whatismyip.com and similar (via cURL).

another option: since most routers allow for telnet connection or have web admin interface, you could login using PHP and just scrape the external IP.

Highly customizable social network platform

Elgg is a good solution. Its the award winning social network platform. If you are familiar with MVC architecture, you can add/ extend / convert elgg into anything which you can imagine.



Related Topics



Leave a reply



Submit