Class: Whatismyip

Inherits:
Object
  • Object
show all
Defined in:
lib/whatismyip.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#public_ipObject (readonly)

Returns the value of attribute public_ip.



6
7
8
# File 'lib/whatismyip.rb', line 6

def public_ip
  @public_ip
end

Class Method Details

.checkObject



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/whatismyip.rb', line 8

def self.check
  %{
  Public IP:
  ==========
  #{public_ip}
  
  Local IP's:
  ===========
  #{display_locals}
  }.map {|l| (l.strip.empty?) ? l : l.lstrip }
end

.display_localsObject



45
46
47
# File 'lib/whatismyip.rb', line 45

def self.display_locals
  local_ips.map { |device, ip| "#{device}: #{ip}\n" }
end

.local_ipsObject



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/whatismyip.rb', line 32

def self.local_ips
  result = `ifconfig`
  
  sections = result.split(/^(?=[^\t])/)
  sections_with_relevant_ip = sections.select{ |i| i =~ /inet/ }
  
  Hash[sections_with_relevant_ip.collect { |section|
    device = section[/[^:]+/]
    ip = section[/inet ([^ ]+)/, 1]
    [device.to_sym, ip]
  }]
end

.public_ipObject



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/whatismyip.rb', line 20

def self.public_ip
  return @public_ip unless @public_ip.nil?
  
  begin
    doc = Nokogiri::HTML(open('http://whatismyip.com/automation/n09230945.asp', 'User-Agent' => "Ruby/#{RUBY_VERSION}"))
    @public_ip = doc.css('p').inner_html
  rescue SocketError => e
    puts "Unable to connect to remote server. Are you sure you're connected to the internet? If not, connect and try again."
    nil
  end
end