Skip to content

Instantly share code, notes, and snippets.

@yob
Created October 12, 2021 03:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yob/e0cbbe2c508b31b36d348a3faad44939 to your computer and use it in GitHub Desktop.
Save yob/e0cbbe2c508b31b36d348a3faad44939 to your computer and use it in GitHub Desktop.
ip-to-as
#!/usr/bin/env ruby
# Small script that converts an IP address into its AS number. Also provides a
# helpful link to Geoff Huston's handy AS summary page
require 'ipaddr'
require 'resolv'
USAGE = "ip-to-as <ipv4/ipv6>"
def get_txt(hostname)
Resolv::DNS.open do |dns|
ress = dns.getresources hostname, Resolv::DNS::Resource::IN::TXT
return ress.map(&:strings).join("\n")
end
return ""
end
if ARGV.size == 0
$stderr.puts USAGE
exit
end
begin
ip = IPAddr.new(ARGV.shift)
rescue IPAddr::InvalidAddressError
$stderr.puts USAGE
exit
end
if ip.ipv4?
hostname = ip.reverse.sub("in-addr.arpa", "origin.asn.cymru.com")
res = get_txt(hostname)
as_number = res[/\A(\d+)/, 1]
elsif ip.ipv6?
hostname = ip.reverse.sub("ip6.arpa", "origin6.asn.cymru.com")
res = get_txt(hostname)
as_number = res[/\A(\d+)/, 1]
else
$stderr.puts USAGE
exit
end
if as_number
puts "IP: #{ip}"
puts "AS: #{as_number}"
res = get_txt("AS#{as_number}.asn.cymru.com")
as, country, registry, date, name = res.gsub('"','').split("|")
puts "country: #{country.strip}"
puts "registry: #{registry.strip}"
puts "date: #{date.strip}"
puts "name: #{name.strip}"
puts "potaroo: http://bgp.potaroo.net/cgi-bin/as-report?as=AS#{as_number}&view=2.0"
else
puts "no result"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment