Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS 

IP Catcher

--Howto use--
the command line:
ruby /path/to/ipcatcher.rb /path/to/filename
the program will print all the ip addresses which is inside the file.
the program doesn't print the same ip address twice. with no duplications.
Done by Amer Jazaerly.there is no copyright.
have fun ;)

#!/usr/bin/ruby

def get_ips(file)
  ips = []
  File.read(file).to_a.each do |place|
    sf = 0
    while sfn = place.index(/(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/,sf)
      sf = sfn + 3
      ips << $&
    end
  end
  return ips
end

get_ips(ARGV[0]).uniq.each { |ip| puts ip }

Convert an integer to IP string

Convert an integer to IP. I don't think you can do this with IPAddr, but I could be wrong

Edit, the original didn't work for low ranges.

And I was wrong about the IPAddr thing. I should have google'd better.

IPAddr.new(16909060, Socket::AF_INET).to_s

Ping a range of IP addresses

(1..254).each {|i| puts ": found 192.168.1.#{i}" if  `ping 192.168.1.#{i} -c 1 -w 1`.match(/ttl/) }

Format IPv4 address in octal binary format and vice versa (Ruby / Rails)

Format an IPv4 address like 192.168.1.1 in dotted binary format like 11000000.10101000.00000001.00000001
You also need this class: http://snippets.dzone.com/posts/show/2472
For Rails: Put this in your controller!


  # convert a dotted decimal IPv4 address to dotted binary format
  def ipv4_to_binary(ipv4addr)
    ia = ipv4addr.to_s.split('.')
    if ia.size != 4
      return "0.0.0.0"
    end
    output = ""
    i = 1
    for octett in ia
      output = output + octett.to_i.to_s(2).using("########","0",true)
      if i < 4
        output = output + "."
      end
      i += 1
    end
    return output
  end
  
  
  # convert a IPv4 adress in binary dotted format to a dotted IPv4 address
  def binary_to_ipv4(ipv4addr)
    ia = ipv4addr.to_s.split('.')
    if ia.size != 4
      return "0.0.0.0"
    end
    output = ""
    i = 1
    for octett in ia
      output = output + octett.to_s.to_i(2).to_s
      if i < 4
        output = output + "."
      end
      i += 1
    end
    return output
  end

Python - My External IP Address

// My external ip address

import urllib

url = urllib.URLopener()
resp = url.open('http://myip.dk')
html = resp.read(114)

end = html.find("</title>")
start = html.find("IP:") + 3

print html[start:end].strip()
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS