6237 Programmering II (Csharp) Agenda/solution 2
From Teknologisk videncenter
class Program
{
static StreamWriter outFile;
static StreamReader inFile;
static List<Log> packets = new List<Log>();
// 47 4.635842000 172.16.236.177 8.8.8.8 DNS 85 Standard query 0x2063 A lh4.googleusercontent.com
static void analyze(List<String> lines)
{
if (lines.Count < 2) return;
//Protokol navnet står fra plads 69 og 9 pladser frem
string protocol = lines[1].Substring(67, 9);
//Tilføj også kode der kan læse Source og Destination
string source = lines[1].Substring(23, 22).Trim();
string dest = lines[1].Substring(45, 22).Trim();
string info = lines[1].Substring(83).Trim();
if (protocol.Trim().ToUpper() == "ARP")
{
}
if (protocol.Trim().ToUpper() == "DNS")
{
//Tilføj kode her der tæller antallet af DNS og gemmer den URL der søges på
if (info.Contains("Standard query 0x")) {
string[] infoSplit = info.Split(' ');
packets.Add(new DnsQ(source, dest, protocol.Trim(), infoSplit[2], infoSplit[5]));
} else
{
string[] infoSplit = info.Split(' ');
var query = packets.Find(x => {
if (x.GetType() == typeof(DnsQ))
return ((DnsQ)x).Id == infoSplit[2];
else
return false;
});
packets.Add(new DnsR(source, dest, protocol.Trim(), (DnsQ)query, info));
}
}
}
static Dictionary<string, int> web = new Dictionary<string, int>();
static void AddWebAddress(String address)
{
if (web.ContainsKey(address))
web[address]++;
else
web[address] = 1;
}
//static void Main(string[] args)
static void Main(string[] args)
{
inFile = new StreamReader("logfile.txt");
outFile = new StreamWriter("outLogs.txt");
String line;
List<String> lines = new List<string>();
while (!inFile.EndOfStream)
{
line = inFile.ReadLine();
//Hvis line starter med No. er det en ny pakke, så skal vi først analysere den gamle
if (line.StartsWith("No.") || inFile.EndOfStream)
{
analyze(lines);
lines = new List<string>();
}
lines.Add(line);
}
inFile.Close();
outFile.Close();
Console.ReadLine();
}
}
public class Log
{
public string Source { get; set; }
public string Destination { get; set; }
public string Protocol { get; set; }
public Log(string source, string destination, string protocol)
{
Source = source;
Destination = destination;
Protocol = protocol;
}
}
public class DnsQ : Log
{
public string Id { get; set; }
public string Url { get; set; }
public DnsQ(string source, string destination, string protocol, string id, string url):base(source, destination, protocol)
{
Id = id;
Url = url;
}
}
public class DnsR : Log
{
public DnsQ Query { get; set; }
private List<string> ipList = new List<string>();
public DnsR(string source, string destination, string protocol, DnsQ query, string infoString):base(source, destination, protocol)
{
Query = query;
bool saveNext = false;
foreach(string s in infoString.Split(' '))
{
if (s == "A") saveNext = true;
else saveNext = false;
if (saveNext)
ipList.Add(s);
}
}
}