Created
June 12, 2024 08:14
-
-
Save sabpprook/23970a2ab6849776e6edc2692fbfa885 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApp2 | |
{ | |
internal class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Stopwatch sw = new Stopwatch(); | |
sw.Start(); | |
ShowCIDR(); | |
sw.Stop(); | |
Console.WriteLine($"Execution Time: {sw.ElapsedMilliseconds}ms"); | |
Console.ReadKey(); | |
} | |
static void ShowCIDR() | |
{ | |
var lines = File.ReadAllLines(@"C:\123123.txt"); | |
var rules = new List<string>(); | |
for (int i = 0; i < lines.Length; i++) | |
{ | |
var line = lines[i].Split('\t'); | |
var ip_start = line[0]; | |
var range = int.Parse(line[2]); | |
Loop: | |
var ip_start_uint = IP2Uint(ip_start); | |
var free_size = FreeSize(ip_start_uint); | |
var pad_size = PaddingSize(free_size, range); | |
var cidr = CIDR(ip_start, pad_size); | |
rules.Add(cidr); | |
if (pad_size < range) | |
{ | |
range -= pad_size; | |
ip_start = Uint2IP(ip_start_uint + (uint)(pad_size << 8)); | |
goto Loop; | |
} | |
} | |
Console.WriteLine(string.Join("\n", rules)); | |
} | |
static uint IP2Uint(string addr) | |
{ | |
var txt = addr.Split('.'); | |
var ip = (uint.Parse(txt[0]) << 24) + (uint.Parse(txt[1]) << 16) + (uint.Parse(txt[2]) << 8) + uint.Parse(txt[3]); | |
return ip; | |
} | |
static string Uint2IP(uint addr) | |
{ | |
return $"{addr >> 24 & 0xFF}.{addr >> 16 & 0xFF}.{addr >> 8 & 0xFF}.{addr & 0xFF}"; | |
} | |
static int FreeSize(uint ip) | |
{ | |
var size = 1; | |
ip >>= 8; | |
while ((ip & 1) == 0) | |
{ | |
ip >>= 1; | |
size <<= 1; | |
} | |
return size; | |
} | |
static int PaddingSize(int free, int range) | |
{ | |
if (free <= range) | |
return free; | |
var i = 2; | |
while (i <= range) | |
{ | |
i <<= 1; | |
} | |
return i / 2; | |
} | |
static string CIDR(string ip, int size) | |
{ | |
var cnt = 0; | |
while (size > 1) | |
{ | |
cnt++; | |
size >>= 1; | |
} | |
return $"{ip}/{24 - cnt}"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://rms.twnic.tw/help_ipv4_assign.php