Skip to content

Instantly share code, notes, and snippets.

@yutopio
Created May 24, 2013 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yutopio/5643946 to your computer and use it in GitHub Desktop.
Save yutopio/5643946 to your computer and use it in GitHub Desktop.
Enumerates IPv4 address space allocation.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
class Program
{
static void Main()
{
var sources = new[] {
// ARIN (American Registry for Internet Numbers)
"ftp://ftp.arin.net/pub/stats/arin/delegated-arin-latest",
// LACNIC (Latin American and Caribbean Internet Addresses Registry)
"ftp://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest",
// APNIC (Asia-Pacific Network Information Centre)
"http://ftp.apnic.net/stats/apnic/delegated-apnic-latest",
// RIPE (Réseaux IP Européens)
"ftp://ftp.ripe.net/ripe/stats/delegated-ripencc-latest",
// AfriNIC
"ftp://ftp.afrinic.net/pub/stats/afrinic/delegated-afrinic-latest" };
var records = new[] { new { Country = "", Start = IPAddress.None, Length = 0 } }.ToList();
records.Clear();
foreach (var source in sources)
{
WebClient request = new WebClient();
byte[] buffer = request.DownloadData(source);
MemoryStream mem = new MemoryStream(buffer);
StreamReader sr = new StreamReader(mem, Encoding.ASCII);
Next:
var line = sr.ReadLine();
if (line == null) continue;
if (line == "" || line[0] == '#') goto Next;
var data = line.Split('|');
if (data[2] == "ipv4" && data[5] != "summary")
records.Add(new {
Country = data[1],
Start = IPAddress.Parse(data[3]),
Length = int.Parse(data[4]) });
goto Next;
}
foreach (var record in (from rec in records
orderby IPtoLong(rec.Start)
select rec))
Console.WriteLine(record.Country + "\t" + record.Start + "\t" + record.Length);
}
static long IPtoLong(IPAddress addr)
{
var bytes = addr.GetAddressBytes();
return ((long)bytes[0] << 24) | ((long)bytes[1] << 16) | ((long)bytes[2] << 8) | (long)bytes[3];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment