-> IPScanner added
-> PortScanner added
This commit is contained in:
104
Networking/IPScannerLib/HiResTimer.cs
Normal file
104
Networking/IPScannerLib/HiResTimer.cs
Normal file
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace IPScanner
|
||||
{
|
||||
public class HiResTimer
|
||||
{
|
||||
private bool isPerfCounterSupported = false;
|
||||
private Int64 frequency = 0;
|
||||
|
||||
// Windows CE native library with QueryPerformanceCounter().
|
||||
private const string lib = "Kernel32.dll";
|
||||
[DllImport(lib)]
|
||||
private static extern int QueryPerformanceCounter(ref Int64 count);
|
||||
[DllImport(lib)]
|
||||
private static extern int QueryPerformanceFrequency(ref Int64 frequency);
|
||||
|
||||
public HiResTimer()
|
||||
{
|
||||
// Query the high-resolution timer only if it is supported.
|
||||
// A returned frequency of 1000 typically indicates that it is not
|
||||
// supported and is emulated by the OS using the same value that is
|
||||
// returned by Environment.TickCount.
|
||||
// A return value of 0 indicates that the performance counter is
|
||||
// not supported.
|
||||
int returnVal = QueryPerformanceFrequency(ref frequency);
|
||||
|
||||
if (returnVal != 0 && frequency != 1000)
|
||||
{
|
||||
// The performance counter is supported.
|
||||
isPerfCounterSupported = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The performance counter is not supported. Use
|
||||
// Environment.TickCount instead.
|
||||
frequency = 1000;
|
||||
}
|
||||
}
|
||||
|
||||
private Int64 Frequency
|
||||
{
|
||||
get
|
||||
{
|
||||
return frequency;
|
||||
}
|
||||
}
|
||||
|
||||
private Int64 Value
|
||||
{
|
||||
get
|
||||
{
|
||||
if (isPerfCounterSupported)
|
||||
{
|
||||
// Get the value here if the counter is supported.
|
||||
Int64 tickCount = 0;
|
||||
QueryPerformanceCounter(ref tickCount);
|
||||
return tickCount;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Otherwise, use Environment.TickCount.
|
||||
return (Int64)Environment.TickCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Int64 start;
|
||||
private bool isRunning = false;
|
||||
private double elapsedMillisecondsAtTimeOfStop = 0;
|
||||
public double ElapsedMilliseconds
|
||||
{
|
||||
get
|
||||
{
|
||||
if (isRunning)
|
||||
{
|
||||
Int64 timeElapsedInTicks = Value - start;
|
||||
return (timeElapsedInTicks * 1000) / Frequency;
|
||||
}
|
||||
else
|
||||
return elapsedMillisecondsAtTimeOfStop;
|
||||
}
|
||||
}
|
||||
public void Start()
|
||||
{
|
||||
start = Value;
|
||||
isRunning = true;
|
||||
}
|
||||
public void Stop()
|
||||
{
|
||||
if (!isRunning)
|
||||
return;
|
||||
elapsedMillisecondsAtTimeOfStop = ElapsedMilliseconds;
|
||||
isRunning = false;
|
||||
}
|
||||
public void Reset()
|
||||
{
|
||||
isRunning = false;
|
||||
elapsedMillisecondsAtTimeOfStop = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
185
Networking/IPScannerLib/HttpHelper.cs
Normal file
185
Networking/IPScannerLib/HttpHelper.cs
Normal file
@@ -0,0 +1,185 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Net;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Reflection;
|
||||
using System.Net.Configuration;
|
||||
|
||||
namespace IPScanner
|
||||
{
|
||||
public class HttpResponseData
|
||||
{
|
||||
public string data;
|
||||
public SortedList<string, string> headers;
|
||||
public string host;
|
||||
public HttpResponseData(string data, SortedList<string, string> headers, string host)
|
||||
{
|
||||
this.data = data;
|
||||
this.headers = headers;
|
||||
this.host = host;
|
||||
}
|
||||
public string GetHeaderValue(string key)
|
||||
{
|
||||
string val;
|
||||
if (headers.TryGetValue(key.ToLower(), out val))
|
||||
return val;
|
||||
return "";
|
||||
}
|
||||
}
|
||||
internal static class HttpHelper
|
||||
{
|
||||
static HttpHelper()
|
||||
{
|
||||
ToggleAllowUnsafeHeaderParsing(true);
|
||||
}
|
||||
public static HttpResponseData GetHttpResponseData(string url)
|
||||
{
|
||||
SortedList<string, string> headers = new SortedList<string, string>();
|
||||
//return new HttpResponseData("", headers, url);
|
||||
byte[] data = GetData(url, headers);
|
||||
return new HttpResponseData(UTF8Encoding.UTF8.GetString(data), headers, url);
|
||||
}
|
||||
/// <summary>
|
||||
/// Gets data from a URL and returns it as a byte array.
|
||||
/// </summary>
|
||||
/// <param name="url"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] GetData(string url, SortedList<string, string> headers = null, string user = "", string password = "", bool keepAlive = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (url.Contains(".80"))
|
||||
{
|
||||
Console.WriteLine(url);
|
||||
}
|
||||
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
|
||||
webRequest.Proxy = null;
|
||||
webRequest.KeepAlive = keepAlive;
|
||||
webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
|
||||
|
||||
if (!string.IsNullOrEmpty(user) || !string.IsNullOrEmpty(password))
|
||||
{
|
||||
string authInfo = user + ":" + password;
|
||||
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
|
||||
webRequest.Headers["Authorization"] = "Basic " + authInfo;
|
||||
}
|
||||
webRequest.Method = "GET";
|
||||
webRequest.Timeout = 5000;
|
||||
webRequest.AllowAutoRedirect = true;
|
||||
return GetResponse(webRequest, headers);
|
||||
}
|
||||
catch (ThreadAbortException ex) { throw ex; }
|
||||
catch (WebException ex)
|
||||
{
|
||||
if (ex.Message.StartsWith("The server committed a protocol violation"))
|
||||
return UTF8Encoding.UTF8.GetBytes(ex.Message);
|
||||
if (ex.Message == "The remote server returned an error: (404) Not Found." || ex.Message == "The remote server returned an error: (401) Unauthorized.")
|
||||
{
|
||||
|
||||
//if(ex.Response.ResponseUri.AbsolutePath == "/nocookies.html")
|
||||
try
|
||||
{
|
||||
return GetResponseData(ex.Response, headers);
|
||||
}
|
||||
catch (ThreadAbortException e) { throw e; }
|
||||
catch (Exception e)
|
||||
{
|
||||
if (url.Contains(".80"))
|
||||
{
|
||||
Console.WriteLine(e.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
//else if (ex.Message == "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel." && url.StartsWith("http:"))
|
||||
//{
|
||||
// url = "https" + url.Substring(4);
|
||||
// return GetData(url, headers, user, password, keepAlive);
|
||||
//}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (url.Contains(".80"))
|
||||
{
|
||||
Console.WriteLine(ex.ToString());
|
||||
}
|
||||
}
|
||||
return new byte[0];
|
||||
}
|
||||
private static byte[] GetResponse(HttpWebRequest webRequest, SortedList<string, string> headers = null)
|
||||
{
|
||||
return GetResponseData((HttpWebResponse)webRequest.GetResponse(), headers);
|
||||
}
|
||||
|
||||
private static byte[] GetResponseData(WebResponse webResponseObj, SortedList<string, string> headers = null)
|
||||
{
|
||||
byte[] data;
|
||||
using (HttpWebResponse webResponse = (HttpWebResponse)webResponseObj)
|
||||
{
|
||||
using (MemoryStream ms = new MemoryStream())
|
||||
{
|
||||
using (Stream responseStream = webResponse.GetResponseStream())
|
||||
{
|
||||
// Dump the response stream into the MemoryStream ms
|
||||
int bytesRead = 1;
|
||||
while (bytesRead > 0)
|
||||
{
|
||||
byte[] buffer = new byte[8000];
|
||||
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
|
||||
if (bytesRead > 0)
|
||||
ms.Write(buffer, 0, bytesRead);
|
||||
}
|
||||
data = new byte[ms.Length];
|
||||
|
||||
// Dump the data into the byte array
|
||||
ms.Seek(0, SeekOrigin.Begin);
|
||||
ms.Read(data, 0, data.Length);
|
||||
responseStream.Close();
|
||||
|
||||
if (headers != null)
|
||||
foreach (string key in webResponse.Headers.AllKeys)
|
||||
headers[key.ToLower()] = webResponse.Headers[key];
|
||||
}
|
||||
}
|
||||
webResponse.Close();
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enable/disable useUnsafeHeaderParsing.
|
||||
/// See http://o2platform.wordpress.com/2010/10/20/dealing-with-the-server-committed-a-protocol-violation-sectionresponsestatusline/
|
||||
/// </summary>
|
||||
/// <param name="enable"></param>
|
||||
/// <returns></returns>
|
||||
public static bool ToggleAllowUnsafeHeaderParsing(bool enable)
|
||||
{
|
||||
//Get the assembly that contains the internal class
|
||||
Assembly assembly = Assembly.GetAssembly(typeof(SettingsSection));
|
||||
if (assembly != null)
|
||||
{
|
||||
//Use the assembly in order to get the internal type for the internal class
|
||||
Type settingsSectionType = assembly.GetType("System.Net.Configuration.SettingsSectionInternal");
|
||||
if (settingsSectionType != null)
|
||||
{
|
||||
//Use the internal static property to get an instance of the internal settings class.
|
||||
//If the static instance isn't created already invoking the property will create it for us.
|
||||
object anInstance = settingsSectionType.InvokeMember("Section", BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });
|
||||
if (anInstance != null)
|
||||
{
|
||||
//Locate the private bool field that tells the framework if unsafe header parsing is allowed
|
||||
FieldInfo aUseUnsafeHeaderParsing = settingsSectionType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
if (aUseUnsafeHeaderParsing != null)
|
||||
{
|
||||
aUseUnsafeHeaderParsing.SetValue(anInstance, enable);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
53
Networking/IPScannerLib/IPRanges.cs
Normal file
53
Networking/IPScannerLib/IPRanges.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace IPScanner
|
||||
{
|
||||
public static class IPRanges
|
||||
{
|
||||
public static List<Tuple<IPAddress, IPAddress>> GetOperationalIPRanges()
|
||||
{
|
||||
List<Tuple<IPAddress, IPAddress>> ranges = new List<Tuple<IPAddress, IPAddress>>();
|
||||
|
||||
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (netInterface.OperationalStatus != OperationalStatus.Up)
|
||||
continue;
|
||||
IPInterfaceProperties ipProps = netInterface.GetIPProperties();
|
||||
foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
|
||||
{
|
||||
if (addr.Address.AddressFamily == AddressFamily.InterNetwork)
|
||||
ranges.Add(new Tuple<IPAddress, IPAddress>(GetLowestInRange(addr.Address, addr.IPv4Mask), GetHighestInRange(addr.Address, addr.IPv4Mask)));
|
||||
}
|
||||
}
|
||||
return ranges;
|
||||
}
|
||||
private static IPAddress GetLowestInRange(IPAddress address, IPAddress mask)
|
||||
{
|
||||
byte[] addressBytes = address.GetAddressBytes();
|
||||
byte[] maskBytes = mask.GetAddressBytes();
|
||||
if (addressBytes.Length != 4 || maskBytes.Length != 4)
|
||||
return IPAddress.None;
|
||||
byte[] lowest = new byte[4];
|
||||
for (var i = 0; i < 4; i++)
|
||||
lowest[i] = (byte)(addressBytes[i] & maskBytes[i]);
|
||||
return new IPAddress(lowest);
|
||||
}
|
||||
private static IPAddress GetHighestInRange(IPAddress address, IPAddress mask)
|
||||
{
|
||||
byte[] addressBytes = address.GetAddressBytes();
|
||||
byte[] maskBytes = mask.GetAddressBytes();
|
||||
if (addressBytes.Length != 4 || maskBytes.Length != 4)
|
||||
return IPAddress.None;
|
||||
byte[] highest = new byte[4];
|
||||
for (var i = 0; i < 4; i++)
|
||||
highest[i] = (byte)((addressBytes[i] & maskBytes[i]) | ~maskBytes[i]);
|
||||
return new IPAddress(highest);
|
||||
}
|
||||
}
|
||||
}
|
||||
29
Networking/IPScannerLib/IPScanResult.cs
Normal file
29
Networking/IPScannerLib/IPScanResult.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Net;
|
||||
|
||||
namespace IPScanner
|
||||
{
|
||||
public class IPScanResult
|
||||
{
|
||||
public IPAddress ip;
|
||||
public int ping = -1;
|
||||
public string host;
|
||||
public ScanStatus status = ScanStatus.Initializing;
|
||||
public string identification = "...";
|
||||
public HttpResponseData response;
|
||||
|
||||
public IPScanResult(IPAddress ip)
|
||||
{
|
||||
this.ip = ip;
|
||||
}
|
||||
//public IPScanResult(IPAddress ip, int ping, string host)
|
||||
//{
|
||||
// this.ip = ip;
|
||||
// this.ping = ping;
|
||||
// this.host = host;
|
||||
// this.status = ScanStatus.Complete;
|
||||
//}
|
||||
}
|
||||
}
|
||||
382
Networking/IPScannerLib/IPTool.cs
Normal file
382
Networking/IPScannerLib/IPTool.cs
Normal file
@@ -0,0 +1,382 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
namespace NetCalc
|
||||
{
|
||||
/// <summary>
|
||||
/// Summary description for IPTool.
|
||||
/// </summary>
|
||||
public class IPTool
|
||||
{
|
||||
// first (0x00) only for fill - so array starts with bit 1
|
||||
static byte[] bit = { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, (byte)0x80 };
|
||||
|
||||
protected string ip = null;
|
||||
protected byte[] ipBytes = null;
|
||||
//protected byte a,b,c,d;
|
||||
protected int networkPrefix; // z.b. 24 for /24
|
||||
protected bool firstSubNetBit = false;
|
||||
|
||||
public IPTool(string ip)
|
||||
{
|
||||
this.setIp(ip);
|
||||
}
|
||||
|
||||
public static byte getBit(int bit)
|
||||
{
|
||||
byte r = 0;
|
||||
if (bit >= 1 && bit <= 8)
|
||||
r = IPTool.bit[bit];
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
public static byte setBit(byte b, int bit)
|
||||
{
|
||||
if (bit >= 1 && bit <= 8)
|
||||
return (byte)(b | IPTool.bit[bit]);
|
||||
else return 0;
|
||||
}
|
||||
|
||||
public static bool isBitSet(byte b, int bit)
|
||||
{
|
||||
bool r = false;
|
||||
if (bit >= 1 && bit <= 8)
|
||||
r = ((b & IPTool.bit[bit]) != 0);
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* return true if domainName is an IP
|
||||
*/
|
||||
static public bool isIP(String domainName)
|
||||
{
|
||||
//if (domainName.matches("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
|
||||
if (domainName.Equals("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
|
||||
return true;
|
||||
else return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* Converts (unsigned)byte to int
|
||||
*/
|
||||
public static int byte2int(byte b)
|
||||
{
|
||||
int i = b;
|
||||
if (b < 0) i = b & 0x7f + 128;
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
// return first byte of IP
|
||||
public byte get1Byte()
|
||||
{
|
||||
return this.ipBytes[0];
|
||||
}
|
||||
|
||||
// return second byte of IP
|
||||
public byte get2Byte()
|
||||
{
|
||||
return this.ipBytes[1];
|
||||
}
|
||||
|
||||
// return third byte of IP
|
||||
public byte get3Byte()
|
||||
{
|
||||
return this.ipBytes[2];
|
||||
}
|
||||
|
||||
// return fourth byte of IP
|
||||
public byte get4Byte()
|
||||
{
|
||||
return this.ipBytes[3];
|
||||
}
|
||||
|
||||
// return array with all bytes of IP
|
||||
public byte[] getBytes()
|
||||
{
|
||||
//return InetAddress.getByName(this.ip).getAddress();
|
||||
//return Dns.GetHostByName(this.ip).AddressList;
|
||||
return IPAddress.Parse(this.ip).GetAddressBytes();
|
||||
}
|
||||
|
||||
public String getIp()
|
||||
{
|
||||
return this.ip;
|
||||
}
|
||||
|
||||
public void setIp(String ip)
|
||||
{
|
||||
this.ip = ip;
|
||||
this.ipBytes = getBytes();
|
||||
this.setPrefix2NetworkClassPrefix();
|
||||
}
|
||||
|
||||
public void setPrefix2NetworkClassPrefix()
|
||||
{
|
||||
this.setNetworkPrefix(this.getNetworkClassPrefix());
|
||||
}
|
||||
|
||||
public int getNetworkClassPrefix()
|
||||
{
|
||||
// set network-prefix with Class-Type
|
||||
int netClass = getNetworkClass();
|
||||
switch (netClass)
|
||||
{
|
||||
case 0: return 8; // Class A
|
||||
case 1: return 16; // Class B
|
||||
case 2: return 24; // Class C
|
||||
//default: setNetworkPrefix(-1); // other Classes have no default Prefix
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* return -1 if out of range (0-255) or other error
|
||||
*/
|
||||
private int convertIPByte(String ipByte)
|
||||
{
|
||||
//int res = Integer.valueOf(ipByte).intValue();
|
||||
int res = Int32.Parse(ipByte);
|
||||
if (res < 0 || res > 255)
|
||||
{
|
||||
res = -1;
|
||||
this.ip = null;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return
|
||||
*/
|
||||
public int getNetworkPrefix()
|
||||
{
|
||||
return this.networkPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param prefix
|
||||
*/
|
||||
public void setNetworkPrefix(int prefix)
|
||||
{
|
||||
this.networkPrefix = prefix;
|
||||
}
|
||||
|
||||
public String getNetworkClassName()
|
||||
{
|
||||
switch (this.getNetworkClass())
|
||||
{
|
||||
case 0: return "Class A";
|
||||
case 1: return "Class B";
|
||||
case 2: return "Class C";
|
||||
case 3: return "Class D/Multicast";
|
||||
case 4: return "Class E/not used";
|
||||
default: return "error";
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 0=Class A
|
||||
* 1=Class B
|
||||
* 2=Class C
|
||||
* 3=Class D
|
||||
* 4=Class E
|
||||
* -1=error
|
||||
*/
|
||||
public int getNetworkClass()
|
||||
{
|
||||
// Test Class A: first bit=0
|
||||
if (!IPTool.isBitSet(this.get1Byte(), 8)) return 0;
|
||||
// Test Class B: first 2bit=10
|
||||
else if (!IPTool.isBitSet(this.get1Byte(), 7)) return 1;
|
||||
// Test Class C: first 3bit=110
|
||||
else if (!IPTool.isBitSet(this.get1Byte(), 6)) return 2;
|
||||
// Test Class D: first 4bit=1110
|
||||
else if (!IPTool.isBitSet(this.get1Byte(), 5)) return 3;
|
||||
// Test Class E: first 4bit=1111 ( = all other)
|
||||
// else if (!IPTool.isBitSet(this.get1Byte(),8)) return 4;
|
||||
else return 4;
|
||||
|
||||
|
||||
/*
|
||||
// Test Class A: first bit=0
|
||||
if ((this.get1Byte() | (byte)0x7f) == (byte)0x7f) return 0;
|
||||
// Test Class B: first 2bit=10
|
||||
if ((this.get1Byte() | 0xbf) == 0xbf) return 1;
|
||||
// Test Class C: first 3bit=110
|
||||
if ((this.get1Byte() | 0xdf) == 0xdf) return 2;
|
||||
// Test Class D: first 4bit=1110
|
||||
if ((this.get1Byte() | 0xef) == 0xef) return 3;
|
||||
// Test Class E: first 4bit=1111
|
||||
if ((this.get1Byte() & 0xf0) == 0xf0) return 4;
|
||||
return -1;
|
||||
*/
|
||||
|
||||
}
|
||||
|
||||
public String getNetworkMask()
|
||||
{
|
||||
return getNetworkMaskByPrefix(this.networkPrefix);
|
||||
}
|
||||
|
||||
public String getNetworkMaskByPrefix(int prefix)
|
||||
{
|
||||
switch (prefix)
|
||||
{
|
||||
case 8: return "255.0.0.0";
|
||||
case 9: return "255.128.0.0";
|
||||
case 10: return "255.192.0.0";
|
||||
case 11: return "255.224.0.0";
|
||||
case 12: return "255.240.0.0";
|
||||
case 13: return "255.248.0.0";
|
||||
case 14: return "255.252.0.0";
|
||||
case 15: return "255.254.0.0";
|
||||
case 16: return "255.255.0.0";
|
||||
case 17: return "255.255.128.0";
|
||||
case 18: return "255.255.192.0";
|
||||
case 19: return "255.255.224.0";
|
||||
case 20: return "255.255.240.0";
|
||||
case 21: return "255.255.248.0";
|
||||
case 22: return "255.255.252.0";
|
||||
case 23: return "255.255.254.0";
|
||||
case 24: return "255.255.255.0";
|
||||
case 25: return "255.255.255.128";
|
||||
case 26: return "255.255.255.192";
|
||||
case 27: return "255.255.255.224";
|
||||
case 28: return "255.255.255.240";
|
||||
case 29: return "255.255.255.248";
|
||||
case 30: return "255.255.255.252";
|
||||
default: return "";
|
||||
}
|
||||
}
|
||||
|
||||
public int getMaxNetworkHosts()
|
||||
{
|
||||
// 2^(32-networkprefix)
|
||||
// -2 ... because .0 and .255
|
||||
return ((int)Math.Pow(2, (32 - this.networkPrefix))) - 2;
|
||||
}
|
||||
|
||||
public int getMaxSubNets()
|
||||
{
|
||||
// Bits from Subnet = prefix-class_prefix
|
||||
|
||||
int count = (int)Math.Pow(2, this.networkPrefix - this.getNetworkClassPrefix());
|
||||
|
||||
// -2 because 1 bit for routing
|
||||
if (!this.isFirstSubNetBit() || this.getNetworkClassPrefix() == this.networkPrefix)
|
||||
count -= 2;
|
||||
|
||||
if (count < 0) count = 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
public long getNetworkLong()
|
||||
{
|
||||
long mask = (long)Math.Pow(2, this.networkPrefix) - 1;
|
||||
mask = mask << (32 - this.networkPrefix);
|
||||
|
||||
return (mask & ip2Long());
|
||||
}
|
||||
|
||||
public String getNetwork()
|
||||
{
|
||||
return long2String(getNetworkLong());
|
||||
}
|
||||
|
||||
public long getBroadCastLong()
|
||||
{
|
||||
long netMask = (long)Math.Pow(2, this.networkPrefix) - 1;
|
||||
netMask = netMask << (32 - this.networkPrefix);
|
||||
long hostMask = (long)Math.Pow(2, 32 - this.networkPrefix) - 1;
|
||||
|
||||
return (netMask = (ip2Long() & netMask) | hostMask);
|
||||
}
|
||||
|
||||
public String getBroadCast()
|
||||
{
|
||||
return long2String(getBroadCastLong());
|
||||
}
|
||||
|
||||
|
||||
public String[] getNetworkIPRange()
|
||||
{
|
||||
String[] result = new String[2];
|
||||
//String from, to;
|
||||
/**
|
||||
* Start
|
||||
* +1 because first = network
|
||||
*/
|
||||
result[0] = long2String(getNetworkLong() + 1);
|
||||
/**
|
||||
* End
|
||||
* -1 because last = broadcast
|
||||
*/
|
||||
result[1] = long2String(getBroadCastLong() - 1);
|
||||
return result;
|
||||
}
|
||||
|
||||
public long ip2Long()
|
||||
{
|
||||
return ((long)(IPTool.byte2int(this.get1Byte()) * 256 +
|
||||
IPTool.byte2int(this.get2Byte())) * 256 +
|
||||
IPTool.byte2int(this.get3Byte())) * 256 +
|
||||
IPTool.byte2int(this.get4Byte());
|
||||
}
|
||||
|
||||
public String long2String(long ip)
|
||||
{
|
||||
long a = (long)(ip & 0xff000000) >> 24;
|
||||
long b = (long)(ip & 0x00ff0000) >> 16;
|
||||
long c = (long)(ip & 0x0000ff00) >> 8;
|
||||
long d = (long)(ip & 0xff);
|
||||
|
||||
return a + "." + b + "." + c + "." + d;
|
||||
}
|
||||
|
||||
public bool isFirstSubNetBit()
|
||||
{
|
||||
return firstSubNetBit;
|
||||
}
|
||||
|
||||
public void setFirstSubNetBit(bool b)
|
||||
{
|
||||
firstSubNetBit = b;
|
||||
}
|
||||
|
||||
public static IPTool getNextIP(String ip)
|
||||
{
|
||||
IPTool nextIp = new IPTool(ip);
|
||||
nextIp.setIp(nextIp.long2String(nextIp.ip2Long() + (long)1));
|
||||
|
||||
return nextIp;
|
||||
|
||||
}
|
||||
|
||||
public IPTool getNextSubNet(long numberOfHosts)
|
||||
{
|
||||
IPTool ip = IPTool.getNextIP(this.getBroadCast());
|
||||
ip.setIp(this.long2String(ip.ip2Long() + (long)1));
|
||||
ip.setFirstSubNetBit(this.isFirstSubNetBit());
|
||||
|
||||
int lastPrefix = ip.getNetworkClassPrefix();
|
||||
|
||||
int prefix = 30;
|
||||
do
|
||||
{
|
||||
if (prefix < ip.getNetworkClassPrefix())
|
||||
return null; // no subnet found
|
||||
ip.setNetworkPrefix(prefix);
|
||||
prefix--;
|
||||
// ignore subnetbit?
|
||||
if (!ip.isFirstSubNetBit() && prefix == lastPrefix + 1) prefix--;
|
||||
|
||||
}
|
||||
while (ip.getMaxNetworkHosts() < numberOfHosts);
|
||||
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
238
Networking/IPScannerLib/NetworkScanner.cs
Normal file
238
Networking/IPScannerLib/NetworkScanner.cs
Normal file
@@ -0,0 +1,238 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using Amib.Threading;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace IPScanner
|
||||
{
|
||||
public class NetworkScanner
|
||||
{
|
||||
private static Regex rxHtmlTitle = new Regex("<title>([^<]+?)</title>", RegexOptions.Compiled);
|
||||
SmartThreadPool Pool = new SmartThreadPool(1000, 256, 0);
|
||||
public NetworkScanner()
|
||||
{
|
||||
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
|
||||
System.Net.ServicePointManager.MaxServicePoints = int.MaxValue;
|
||||
}
|
||||
|
||||
public List<IPScanResult> BeginScan(IPAddress ipFrom, IPAddress ipTo)
|
||||
{
|
||||
Amib.Threading.Action<IPAddress, List<IPScanResult>, int> ipScanAction = new Amib.Threading.Action<IPAddress, List<IPScanResult>, int>(ScanIPAsync);
|
||||
// Count the IP addresses included in this range
|
||||
byte[] addyEnd = ipTo.GetAddressBytes();
|
||||
byte[] addyNext = ipFrom.GetAddressBytes();
|
||||
|
||||
List<IPScanResult> Results = new List<IPScanResult>();
|
||||
while (CompareIPs(addyNext, addyEnd) < 1)
|
||||
{
|
||||
Results.Add(new IPScanResult(new IPAddress(addyNext)));
|
||||
IncrementIP(addyNext);
|
||||
}
|
||||
|
||||
for (int i = 0; i < Results.Count; i++)
|
||||
Pool.QueueWorkItem(ipScanAction, Results[i].ip, Results, i);
|
||||
return Results;
|
||||
}
|
||||
private void ScanIPAsync(IPAddress ip, List<IPScanResult> results, int listIndex)
|
||||
{
|
||||
bool foundHost = false;
|
||||
results[listIndex].status = ScanStatus.Initializing;
|
||||
|
||||
// Attempt Ordinary Ping
|
||||
try
|
||||
{
|
||||
using (Ping p = new Ping())
|
||||
{
|
||||
PingReply pingReply = p.Send(ip, 5000);
|
||||
if (pingReply.Status == IPStatus.Success)
|
||||
{
|
||||
foundHost = true;
|
||||
results[listIndex].status = ScanStatus.Partial;
|
||||
results[listIndex].ping = (int)pingReply.RoundtripTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
|
||||
// Attempt DNS Lookup
|
||||
try
|
||||
{
|
||||
Stopwatch timer = new Stopwatch();
|
||||
timer.Start();
|
||||
IPHostEntry ipe = Dns.GetHostEntry(ip);
|
||||
timer.Stop();
|
||||
int dnsLookupTime = (int)timer.ElapsedMilliseconds;
|
||||
|
||||
foundHost = true;
|
||||
//if (results[listIndex].ping < 0 || dnsLookupTime < results[listIndex].ping)
|
||||
// results[listIndex].ping = dnsLookupTime;
|
||||
results[listIndex].host = ipe.HostName.ToString();
|
||||
results[listIndex].status = ScanStatus.Complete;
|
||||
}
|
||||
//catch (SocketException ex)
|
||||
//{
|
||||
// //if (ex.SocketErrorCode == SocketError.HostNotFound)
|
||||
// // return;
|
||||
// Console.WriteLine(ex.Message);
|
||||
//}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (foundHost)
|
||||
{
|
||||
// Try to identify
|
||||
HttpResponseData response;
|
||||
results[listIndex].identification = IdentifyHost(ip, out response);
|
||||
results[listIndex].status = ScanStatus.Complete;
|
||||
results[listIndex].response = response;
|
||||
}
|
||||
else
|
||||
results[listIndex].status = ScanStatus.NotFound;
|
||||
}
|
||||
|
||||
private string IdentifyHost(IPAddress ip, out HttpResponseData response)
|
||||
{
|
||||
response = null;
|
||||
Stopwatch sw = new Stopwatch();
|
||||
try
|
||||
{
|
||||
sw.Start();
|
||||
response = HttpHelper.GetHttpResponseData("http://" + ip.ToString() + "/");
|
||||
if (response.GetHeaderValue("server").StartsWith("lighttpd") && response.GetHeaderValue("set-cookie").Contains("AIROS_") && response.data.Contains("<title>Error 404"))
|
||||
return "Ubiquiti";
|
||||
else if (response.GetHeaderValue("server").StartsWith("Boa") && response.data.Contains("<OBJECT ID=\"TSConfigIPCCtrl\""))
|
||||
return "Generic IP Cam"; // CCDCam EC-IP5911
|
||||
else if (response.data.Contains("flow_slct = get_slctid('flowtype');"))
|
||||
return "IPS Cam";
|
||||
else if (response.GetHeaderValue("server") == "GoAhead-Webs" && response.data.Contains("document.location = '/live.asp?"))
|
||||
return "Edimax Cam";
|
||||
else if (response.GetHeaderValue("server").StartsWith("App-webs/") && response.data.Contains("window.location.href = \"doc/page/login.asp"))
|
||||
return "Hikvision";
|
||||
else if (response.data.Contains("src=\"jsCore/LAB.js\"") || response.data.Contains("var lt = \"?WebVersion=") || response.data.Contains("src=\"jsCore/rpcCore.js"))
|
||||
return "Dahua";
|
||||
else if (response.GetHeaderValue("www-authenticate").Contains("realm=\"tomato\""))
|
||||
return "Tomato";
|
||||
else if (response.GetHeaderValue("server") == "Web Server" && response.data.Contains("<TITLE>NETGEAR FS728TP</TITLE>"))
|
||||
return "Netgear FS728TP";
|
||||
else if (response.GetHeaderValue("set-cookie").Contains("DLILPC=") && response.data.Contains("<title>Power Controller"))
|
||||
return "Web Power Switch";
|
||||
else if (response.data == "The server committed a protocol violation. Section=ResponseStatusLine")
|
||||
return "? WeatherDirect ?";
|
||||
else if (response.data == "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF")
|
||||
return "? Web Power Switch ?";
|
||||
else if (response.data.Contains("NetDAQ ND-100"))
|
||||
return "NetDAQ ND-100";
|
||||
else if (response.GetHeaderValue("server") == "nginx" && response.data.Contains("<title>airVision:"))
|
||||
return "AirVision NVR";
|
||||
else if (response.GetHeaderValue("server") == "nginx" && response.data.Contains("<title>airVision:"))
|
||||
return "AirVision NVR";
|
||||
else if (response.GetHeaderValue("server").StartsWith("BlueIris-"))
|
||||
return "Blue Iris";
|
||||
//else if (response.data.Contains("<title>iTach"))
|
||||
// return "iTach";
|
||||
else if (response.data.Contains("href=\"/cmh\""))
|
||||
return "Vera";
|
||||
else if (response.data.Contains("WDMyCloud"))
|
||||
return "WDMyCloud";
|
||||
//else if (response.data.Contains("<title>DD-WRT"))
|
||||
// return "DD-WRT";
|
||||
else if (response.data.Contains("= \"Peplink\""))
|
||||
return "Peplink";
|
||||
else if (response.data.Contains("GSViewerX.ocx"))
|
||||
return "GrandStream";
|
||||
else if (response.data.Contains("content=\"Canon Inc.\""))
|
||||
return "Canon printer";
|
||||
else if (response.GetHeaderValue("server") == "tsbox" && response.GetHeaderValue("www-authenticate") == "Basic realm=\"pbox\"")
|
||||
return "HDMI Encoder";
|
||||
else if (response.data.Contains("Rules of login password.\\n"))
|
||||
return "ACTi";
|
||||
else if (response.data.Contains("/static/freenas_favicon.ico"))
|
||||
return "FreeNAS";
|
||||
else if (response.data.Contains("CONTENT=\"0;url=cgi-bin/kvm.cgi\""))
|
||||
return "Avocent KVM";
|
||||
else if (response.GetHeaderValue("www-authenticate") == "Basic realm=\"TomatoUSB\"")
|
||||
return "TomatoUSB Router";
|
||||
else if (response.GetHeaderValue("auther") == "Steven Wu" && response.GetHeaderValue("server") == "Camera Web Server/1.0" && response.data.Contains("location.href=\"top.htm?Currenttime=\"+timeValue;"))
|
||||
return "TrendNET IP cam";
|
||||
else if (response.data.Contains(@"<meta http-equiv=""refresh"" content=""0;URL='/ui'""/>"))
|
||||
return "ESXi";
|
||||
else if (response.GetHeaderValue("server") == "Microsoft-HTTPAPI/2.0")
|
||||
return "IIS";
|
||||
else
|
||||
{
|
||||
Match m = rxHtmlTitle.Match(response.data);
|
||||
if (m.Success)
|
||||
return m.Groups[1].Value;
|
||||
string server = response.GetHeaderValue("server");
|
||||
if (!string.IsNullOrEmpty(server))
|
||||
return server;
|
||||
return "";
|
||||
}
|
||||
return response.data;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
sw.Stop();
|
||||
//Console.WriteLine("Spent " + sw.ElapsedMilliseconds + " on " + response.data.Length);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public void Abort()
|
||||
{
|
||||
Pool.Cancel(true);
|
||||
}
|
||||
bool ArraysMatch(Array a1, Array a2)
|
||||
{
|
||||
if (a1.Length != a2.Length)
|
||||
return false;
|
||||
for (int i = 0; i < a1.Length; i++)
|
||||
if (a1.GetValue(i) != a1.GetValue(i))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
int CompareIPs(byte[] ip1, byte[] ip2)
|
||||
{
|
||||
if (ip1 == null || ip1.Length != 4)
|
||||
return -1;
|
||||
if (ip2 == null || ip2.Length != 4)
|
||||
return 1;
|
||||
int comp = ip1[0].CompareTo(ip2[0]);
|
||||
if (comp == 0)
|
||||
comp = ip1[1].CompareTo(ip2[1]);
|
||||
if (comp == 0)
|
||||
comp = ip1[2].CompareTo(ip2[2]);
|
||||
if (comp == 0)
|
||||
comp = ip1[3].CompareTo(ip2[3]);
|
||||
return comp;
|
||||
}
|
||||
void IncrementIP(byte[] ip, int idx = 3)
|
||||
{
|
||||
if (ip == null || ip.Length != 4 || idx < 0)
|
||||
return;
|
||||
if (ip[idx] == 254)
|
||||
{
|
||||
ip[idx] = 1;
|
||||
IncrementIP(ip, idx - 1);
|
||||
}
|
||||
else
|
||||
ip[idx] = (byte)(ip[idx] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
15
Networking/IPScannerLib/ScanStatus.cs
Normal file
15
Networking/IPScannerLib/ScanStatus.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace IPScanner
|
||||
{
|
||||
public enum ScanStatus
|
||||
{
|
||||
Initializing,
|
||||
Scanning,
|
||||
NotFound,
|
||||
Complete,
|
||||
Partial
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user