using Microsoft.Data.SqlClient; using BlockIPAddr.ClassObj; using static BlockIPAddr.ClassObj.ANSI; namespace BlockIPAddr; internal class Program { [STAThread] static void Main(string[] args) { ConsoleColorization.Initialize(); // Allow ANSI in the console if (args.Length > 0) { Console.WriteLine(); using (var cn = new SqlConnection(kmCommonLibsCore.Constants.cnPortal)) using (var cm = new SqlCommand("dbo.[BlockIPAddrInFirewall]", cn) { CommandType = System.Data.CommandType.StoredProcedure }) { cn.Open(); cm.Parameters.Add("@ip4", System.Data.SqlDbType.VarChar, 30); foreach (string arg in args) { string rv; string color = string.Empty; if (!IsValid(arg)) Console.WriteLine("{0}ERROR: '{1}{2}{0}' is not a valid IP4 address.{3}", ANSI.fgBrightRed, ANSI.fgBrightWhite, arg.Trim(), ANSI.fgReset); else { cm.Parameters["@ip4"].Value = arg.Trim(); rv = cm.ExecuteScalar().ToString() ?? string.Empty; color = rv.StartsWith("!!") ? ANSI.fgBrightRed : ANSI.fgBrightYellow; Console.WriteLine("Result: {1}{0}{2}", rv, color, ANSI.fgReset); } } } } else { while (true) { string? ip4 = string.Empty; Console.Write("\nEnter an IP Address to block (can include slash-notation) or Enter to Exit: "); ip4 = Console.ReadLine(); if (string.IsNullOrWhiteSpace(ip4)) break; if (!IsValid(ip4)) Console.WriteLine("\n{0}ERROR: '{1}{2}{0}' is not a valid IP4 address.{3}", ANSI.fgBrightRed, ANSI.fgBrightWhite, ip4, ANSI.fgReset); else { using (var cn = new SqlConnection(kmCommonLibsCore.Constants.cnPortal)) using (var cm = new SqlCommand("dbo.[BlockIPAddrInFirewall]", cn) { CommandType = System.Data.CommandType.StoredProcedure }) { string color = string.Empty; string rv = string.Empty; cn.Open(); cm.Parameters.Add("@ip4", System.Data.SqlDbType.VarChar, 30).Value = ip4; rv = cm.ExecuteScalar().ToString() ?? string.Empty; color = rv.StartsWith("!!") ? ANSI.fgBrightRed : ANSI.fgBrightYellow; Console.WriteLine("\nResult: {1}{0}{2}", rv, color, ANSI.fgReset); } } } } } static internal bool IsValid(string ip) { bool rv = false; try { if (ip.IndexOf('/') > 0) // prevent it from being the first character { string[] part = ip.Split('/'); if (part.Length != 2) rv = false; else { System.Net.IPAddress? ip4 = null; byte subMask = 0; if (System.Net.IPAddress.TryParse(part[0].Trim(), out ip4)) rv = true; if (rv && byte.TryParse(part[1].Trim(), out subMask)) rv = true; else rv = false; } } else { System.Net.IPAddress? ip4 = null; if (System.Net.IPAddress.TryParse(ip.Trim(), out ip4)) rv = true; else rv = false; } } catch //(Exception) { rv = false; } return rv; } }