martedì 3 giugno 2008

Confrontare IP con C#

In questo momento non ho tempo per approfondire l'argomento cmq se avete bisogno di confrontare due indirizzi ip o per controllare se un indirizzo ip appartiene ad un range di indirizzi ip ho scritto un pò di codice:

using System;
using System.Text;

namespace IPManager
{
class Program
{
static void Main(string[] args)
{
string cmd;
Console.WriteLine("^^^^^^^^^^^^PROG DI TEST PER IP^^^^^^^^^^^^");
Console.WriteLine("-> INSERISCI UN IP NEL FORMATO 192.168.1.1: ");
cmd = Console.ReadLine();
IPAddress ip = new IPAddress(cmd);
Console.WriteLine("-> HAI INSERITO: " + ip.ToString() + "");
Console.WriteLine("-> LO CONVERTO IN LONG: " + ip.Parse(ip.ToString()).ToString() + "");
Console.WriteLine("----------------------------------------");
Console.WriteLine("-> INSERISCI UN RANGE DI IP PER: " + ip.ToString() + "");
Console.WriteLine("-> DA: ");
cmd = Console.ReadLine();
IPAddress ipA = new IPAddress(cmd);
Console.WriteLine("-> A: ");
cmd = Console.ReadLine();
IPAddress ipB = new IPAddress(cmd);
if (ip.isInRange(ipA, ipB))
{
Console.WriteLine("-> " + ip.ToString() + " E' NEL RANGE!");
}
else
{
Console.WriteLine("-> " + ip.ToString() + ">NON< E' NEL RANGE!");
}
}
}
class IPAddress
{
private string ipStr;
public long NumericIPAddress
{
get { return ipNum; }
set { ipNum = value; }
}
private long ipNum;

public IPAddress(string ipAddress)
{
this.ipStr = ipAddress;
this.ipNum = this.Parse(ipAddress);
}

public long Parse(string ipAddress)
{
string[] arr;
arr = ipAddress.Split('.');
return (long.Parse(arr[0]) * 16777216) + (long.Parse(arr[1]) * 65536) + (long.Parse(arr[2]) * 256) + long.Parse(arr[3]);
}
public bool isInRange(IPAddress ipA, IPAddress ipB)
{
if ((ipA.ipNum <= this.ipNum) && (ipB.ipNum >= this.ipNum))
{
return true;
}
else
{
return false;
}
}
public override string ToString()
{
return ipStr;
}
}
}

2 commenti:

Jagger ha detto...

Ma c'è un sito che già fa ste cose...XD

Ps. Blogger per postare codice fa veramente schifo

IndexOut ha detto...

tipo? ti dice se un ip è compreso in un range? Ma perchè non leggi prima di postare? Incompetente!