public static void Trace(Packet packet, PacketMonitorForm PacketMonitor) { IpPacket ipPacket = null; TcpPacket tcpPacket = null; try { ipPacket = PacketDotNet.IpPacket.GetEncapsulated(packet); if (ipPacket == null || ipPacket.Version == IpVersion.IPv6) { return; } tcpPacket = PacketDotNet.TcpPacket.GetEncapsulated(packet); if (tcpPacket == null) { return; } long Key = ipPacket.SourceAddress.Address + tcpPacket.SourcePort + ipPacket.DestinationAddress.Address + tcpPacket.AcknowledgmentNumber; if (isReassembledPacketOfPostRequest(ipPacket, tcpPacket)) { PacketReassemble(Key, tcpPacket); MailList[Key].TimeToLive = 0; // Var_PushFlag == true 表示資料都已經擷取完全 if (MailList[Key].Var_PushFlag == true) { var Mail = MailList[Key]; foreach (var Data in Mail.PostRequestDataList) { Mail.PostRequestData += new string(Data); } foreach (var Data in Mail.VarDataList) { Mail.VarData += new string(Data); } DoSomething(Mail, PacketMonitor); MailList.Remove(Key); } } else if (isPostRequest(tcpPacket)) { MailList.Add(Key, new HttpMail(ipPacket, tcpPacket)); } else { return; } AddMailLiveTime(); } catch { Console.WriteLine(); return; } }
static void Program_OnPacketArrival(object sender, CaptureEventArgs e) { Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); // получение только TCP пакета из всего фрейма var tcpPacket = TcpPacket.GetEncapsulated(packet); // получение только IP пакета из всего фрейма var ipPacket = IpPacket.GetEncapsulated(packet); if (tcpPacket != null && ipPacket != null) { // IP адрес получателя var dstIp = ipPacket.DestinationAddress.ToString(); // порт отправителя var srcPort = tcpPacket.SourcePort.ToString(); dataPacket = tcpPacket.ParentPacket.ToString(); if (dataPacket != null) { foreach (var port in buff) { if (srcPort == port) { Int32.TryParse(portOfProces, out portForBloc); packageDetected = true; } } } } }
public PackageDetail(TcpPacket tcpPacket, UdpPacket udpPacket, IpPacket ipPacket) { Id = Interlocked.Increment(ref _newId); TcpPacket = tcpPacket; UdpPacket = udpPacket; IpPacket = ipPacket; }
/// <summary> /// Runs the scenario. /// </summary> public override void Run() { Host H1 = new Host("H1"), H2 = new Host("H2"); H1.RegisterInterface(new Interface(new Nic( new MacAddress("AA:AA:AA:AA:AA:AA")), "eth0", "192.168.1.2/24", "192.168.1.1")); H2.RegisterInterface(new Interface(new Nic( new MacAddress("BB:BB:BB:BB:BB:BB")), "eth0", "192.168.1.3/24", "192.168.1.1")); // Attach both stations to a "thick" Ethernet 10BASE5 cable. new C10Base5(250) .Pierce(0, H1.Interfaces["eth0"].Nic.Connector) .Pierce(250, H2.Interfaces["eth0"].Nic.Connector); var dummyPacket1 = new IpPacket(new IpAddress("192.168.1.3"), new IpAddress("192.168.1.2"), IpProtocol.Tcp, new byte[] { 1, 2, 3, 4 }); var dummyPacket2 = new IpPacket(new IpAddress("192.168.1.2"), new IpAddress("192.168.1.3"), IpProtocol.Tcp, new byte[] { 1, 2, 3, 4 }); // Station H1 triggers a transmission at time t = 0ns. Simulation.Callback(0, () => { H1.Interfaces["eth0"].Output(new MacAddress("BB:BB:BB:BB:BB:BB"), dummyPacket1.Serialize()); }); // Station H2 triggers a transmissin at time t = 1000ns. Simulation.Callback(1000, () => { H2.Interfaces["eth0"].Output(new MacAddress("AA:AA:AA:AA:AA:AA"), dummyPacket2.Serialize()); }); Simulation.AddObject(H1.Hostname, H1); Simulation.AddObject(H2.Hostname, H2); Simulation.Start(); }
// tcp public void VerifyPacket0(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual(PhysicalAddress.Parse("00-13-10-03-71-47"), e.SourceHwAddress); Assert.AreEqual(PhysicalAddress.Parse("00-E0-4C-E5-73-AD"), e.DestinationHwAddress); IpPacket ip = (IpPacket)e.PayloadPacket; Assert.AreEqual(System.Net.IPAddress.Parse("82.165.240.134"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.221"), ip.DestinationAddress); Assert.AreEqual(IpVersion.IPv4, ip.Version); Assert.AreEqual(IPProtocolType.TCP, ip.Protocol); Assert.AreEqual(254, ip.TimeToLive); Assert.AreEqual(0x0df8, ((IPv4Packet)ip).CalculateIPChecksum()); Assert.AreEqual(1176685346, rawCapture.Timeval.Seconds); Assert.AreEqual(885259.000, rawCapture.Timeval.MicroSeconds); TcpPacket tcp = (TcpPacket)ip.PayloadPacket; Assert.AreEqual(80, tcp.SourcePort); Assert.AreEqual(4324, tcp.DestinationPort); Assert.IsTrue(tcp.Ack); Assert.AreEqual(3536, tcp.WindowSize); Assert.AreEqual(0xc835, tcp.CalculateTCPChecksum()); Console.WriteLine("tcp.Checksum is {0}", tcp.Checksum); Assert.AreEqual(0xc835, tcp.Checksum, "tcp.Checksum mismatch"); Assert.IsTrue(tcp.ValidTCPChecksum); }
public void IgmpPacketCapture(object sender, CaptureEventArgs e) //Packet capture and return to string (async) { RawCapture capturePacket = e.Packet; try { if (this.NowCaptureNum <= this.CaptureNum) { var packet = PacketDotNet.Packet.ParsePacket(capturePacket.LinkLayerType, capturePacket.Data); IpPacket ipPacket = (IpPacket)packet.Extract(typeof(PacketDotNet.IpPacket)); if (ipPacket.Version != IpVersion.IPv4 || ipPacket.Protocol != IPProtocolType.IGMP) { return; } IGMPv2Packet igmpPacket = (IGMPv2Packet)ipPacket.Extract(typeof(PacketDotNet.IGMPv2Packet)); this.NowCaptureNum++; ResultData += "Header:" + igmpPacket.Header + "\n"; int i = 1; if (igmpPacket.PayloadData != null) { foreach (byte data in igmpPacket.PayloadData) { ResultData += Convert.ToString(data, 16) + " "; if (i % 8 == 0) { ResultData += "\n"; } i++; } } ResultData += "\n--------------------------------------------\n"; if (this.NowCaptureNum == this.CaptureNum) { StopPacketCapture(); } SendPacketData(); } else { StopPacketCapture(); //PacketCaptureDevice.Close(); CaptureEndEvent(); } } catch (NullReferenceException nullException) { Console.WriteLine(nullException.StackTrace); MessageBox.Show("Can't packet extracted. \n Are you set others protocol in filter?" , "Warining", System.Windows.MessageBoxButton.OK); StopPacketCapture(); //PacketCaptureDevice.Close(); } }
// filter-event private void capture_event6(object sender, CaptureEventArgs e) { Packet p = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); IpPacket ip = (IpPacket)p.Extract(typeof(IpPacket)); TcpPacket tcp = (TcpPacket)p.Extract(typeof(TcpPacket)); UdpPacket udp = (UdpPacket)p.Extract(typeof(UdpPacket)); s = device.Statistics; if (udp != null) { m.WaitOne(); string time = DateTime.Now.ToString(time_format); int length = e.Packet.Data.Length; string source = ip.SourceAddress.ToString(); string destinition = ip.DestinationAddress.ToString(); var protocol = ip.Protocol; string data = p.PrintHex(enc); string mes = p.GetData(ip.HeaderLength); if (mes.Contains(message)) { object[] row = new object[] { time, length, source, destinition, protocol, data }; dataGridView1.Rows.Add(row); catched++; } label2.Text = ""; label3.Text = ""; label4.Text = ""; m.ReleaseMutex(); } label2.Text = "Received Packets: " + Convert.ToString(s.ReceivedPackets); label3.Text = "Dropped Packets: " + Convert.ToString(s.DroppedPackets); label4.Text = "Interface Dropped Packets: " + Convert.ToString(s.InterfaceDroppedPackets); label6.Text = "Catched Packets: " + Convert.ToString(catched); }
/// <summary> /// Dumps each received packet to a pcap file /// </summary> private static void device_PcapOnPacketArrival(object sender, SharpPcap.CaptureEventArgs e) { SyslogMessage msg = null; try { Packet link = Packet.ParsePacket(LinkLayers.Ethernet, e.Packet.Data); EthernetPacket ethernet = (EthernetPacket)link; IpPacket ip = (IpPacket)ethernet.PayloadPacket; UdpPacket udp = (UdpPacket)ip.PayloadPacket; msg = new SyslogMessage(udp); outputFile.WriteLine(System.Text.Encoding.ASCII.GetString(udp.PayloadData)); } catch (Exception ex) { EventLog.WriteEntry("SwsyslogService", ex.ToString(), EventLogEntryType.Error); } // if the output file is ready to write, write the log file ... if (msg != null && outputFile.BaseStream.CanWrite) { //outputFile.WriteLine(msg.ToString()); } _logEntryCount++; }
/// <summary> /// 通过PacketDotNet类库实现 /// </summary> /// <param name="ppp"></param> private void PPP(PacketDotNet.PPPPacket ppp) { if (PPPNode == null) { PPPNode = CreatNode("PPP", 10); } PPPNode.Text = "PPP [0x" + ((ushort)ppp.Protocol).ToString("X4") + "]"; PPPNode.Nodes.Clear(); PPPNode.Nodes.Add("Protocol: " + ppp.Protocol.ToString() + " [0x" + ppp.Protocol.ToString("X") + "]"); Tree.Nodes.Add(PPPNode); switch (ppp.Protocol) { case PPPProtocol.IPv4: case PPPProtocol.IPv6: IpPacket ip = IpPacket.GetEncapsulated(packet); IP(ip); break; case PPPProtocol.LCP: LCPPacket lcp = LCPPacket.GetEncapsulated(packet); LCP(lcp); break; case PPPProtocol.CompressedDatagram: ExtraData(ppp.PayloadData); return; case PPPProtocol.Padding: //填充 break; } }
// Test private void capture_event4(object sender, CaptureEventArgs e) { m.WaitOne(); Packet p = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); IpPacket ip = (IpPacket)p.Extract(typeof(IpPacket)); UdpPacket udp = (UdpPacket)p.Extract(typeof(UdpPacket)); if (udp != null) { string time = DateTime.Now.ToString(time_format); int length = e.Packet.Data.Length; int offset = ip.HeaderLength; string source = ip.SourceAddress.ToString(); string destinition = ip.DestinationAddress.ToString(); var protocol = ip.Protocol; string data = p.PrintHex(enc); object[] row = new object[] { time, length, source, destinition, protocol, data }; dataGridView1.Rows.Add(row); if (destinition == this.ip.ToString()) { dataGridView1.Rows[catched].DefaultCellStyle.BackColor = Color.Pink; } catched++; } m.ReleaseMutex(); }
public void ReportPacketCapture(Packet packet, DateTime arrivalTime) { IpPacket ip = (IpPacket)packet.Extract(typeof(IpPacket)); TcpPacket tcp = (TcpPacket)packet.Extract(typeof(TcpPacket)); ASCIIEncoding format = new ASCIIEncoding(); string payloadAsText = format.GetString(packet.Bytes); payloadAsText = payloadAsText.ToLower(); //remove non readable characters //payloadAsText = Regex.Replace(payloadAsText, @"[^\u0000-\u007F]", string.Empty); payloadAsText = Regex.Replace(payloadAsText, "[^0-9a-zA-Z]+", string.Empty); if ((tcp != null) && (payloadAsText.Contains("ftp"))) { int x = 5; } if (payloadAsText.Length > 255) { payloadAsText = payloadAsText.Substring(0, 255); } if (tcp != null) { _sensorEventAgent.LogEvent(_sensorId, ip.DestinationAddress.ToString(), tcp.DestinationPort, ip.SourceAddress.ToString(), tcp.SourcePort, arrivalTime, payloadAsText); } }
override public ForwardingDecision process_packet(int in_port, ref Packet packet) { if (packet is EthernetPacket && packet.Encapsulates(typeof(IPv4Packet), typeof(UdpPacket), typeof(Paxos_Packet))) { IpPacket ip_p = ((IpPacket)(packet.PayloadPacket)); UdpPacket udp_p = ((UdpPacket)(ip_p.PayloadPacket)); if (udp_p.DestinationPort == Paxos.Paxos_Coordinator_Port) { Paxos_Packet paxos_p = ((Paxos_Packet)(udp_p.PayloadPacket)); instance_register++; paxos_p.Instance = instance_register; udp_p.DestinationPort = Paxos.Paxos_Acceptor_Port; udp_p.UpdateUDPChecksum(); // NOTE we could use "udp_p.Checksum = 0" to // follows the P4 implementation, // avoiding the (optional) UDP checksum. // Same applies to instances of // checksum-setting below. } } // We assume that we receive from in_port and send to in_port+1. // NOTE that we implicitly forward all non-Paxos packets onwards, // unmmodified. The downstream processor then decides how to forward // them along the network. return(new ForwardingDecision.SinglePortForward(in_port + 1)); }
override public ForwardingDecision process_packet(int in_port, ref Packet packet) { //Check if the packet is of the form we're interested in. if (packet is EthernetPacket && packet.Encapsulates(typeof(IPv4Packet), typeof(UdpPacket), typeof(Paxos_Packet))) { IpPacket ip_p = ((IpPacket)(packet.PayloadPacket)); UdpPacket udp_p = ((UdpPacket)(ip_p.PayloadPacket)); if (udp_p.DestinationPort == Paxos.Paxos_Acceptor_Port) { Paxos_Packet paxos_p = ((Paxos_Packet)(udp_p.PayloadPacket)); ingress_metadata_t local_metadata; read_round(out local_metadata, paxos_p); if (local_metadata.round <= paxos_p.Round) { acceptor(ref udp_p, ref paxos_p); } } } // We follow the same forwarding policy as the Coordinator. return(new ForwardingDecision.SinglePortForward(in_port + 1)); }
public void ScanDhcp(CaptureEventArgs e, string Interface) { var mypacket = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); var udp = (UdpPacket)mypacket.Extract(typeof(UdpPacket)); if (udp != null) { if (udp.DestinationPort == 68) { var DestinationHwAddress = EthernetPacket.GetEncapsulated(mypacket).DestinationHwAddress; var SourceHwAddress = EthernetPacket.GetEncapsulated(mypacket).SourceHwAddress; var DestinationipAddress = IpPacket.GetEncapsulated(mypacket).DestinationAddress; var SourceipAddress = IpPacket.GetEncapsulated(mypacket).SourceAddress; ado a = new ado(); DataTable dt = a.selectmac(SourceHwAddress.ToString(), Interface); // if mac address of router excist that mean he is router if (dt.Rows.Count > 0) { Attack = false; } else { Attack = true; Attack_data[0] = "DHCP spofing"; Attack_data[1] = SourceipAddress.ToString(); Attack_data[2] = SourceHwAddress.ToString(); Attack_data[3] = DateTime.Now.ToShortTimeString(); } } } }
void Inject(NetworkSniffer sniffer, TcpStream stream, Packet[] packets) { WriteInfo("Injecting packets"); foreach (EthernetPacket p in packets) { // Override ethernet p.DestinationHwAddress = stream.DestinationHwAddress; p.SourceHwAddress = stream.SourceHwAddress; p.UpdateCalculatedValues(); IpPacket ip = (IpPacket)p.PayloadPacket; ip.SourceAddress = stream.Source.Address; ip.DestinationAddress = stream.Destination.Address; ip.UpdateCalculatedValues(); if (ip.Protocol != IPProtocolType.TCP) { continue; } TcpPacket tcp = (TcpPacket)ip.PayloadPacket; tcp.SourcePort = (ushort)stream.Source.Port; tcp.DestinationPort = (ushort)stream.Destination.Port; tcp.UpdateCalculatedValues(); // Send sniffer.Send(p); } }
private void ipNext(IpPacket ip) { switch (ip.NextHeader) { case IPProtocolType.TCP: TcpPacket tcp = (TcpPacket)ip.Extract(typeof(TcpPacket)); TCP(tcp); break; case IPProtocolType.UDP: UdpPacket udp = (UdpPacket)ip.Extract(typeof(UdpPacket)); UDP(udp); break; case IPProtocolType.ICMP: ICMPv4Packet icmp = (ICMPv4Packet)ip.Extract(typeof(ICMPv4Packet)); ICMP(icmp); break; case IPProtocolType.ICMPV6: ICMPv6Packet icmpv6 = (ICMPv6Packet)ip.Extract(typeof(ICMPv6Packet)); ICMPv6(icmpv6); break; case IPProtocolType.IGMP: break; default: break; } }
public static SnmpDatagram GetSnmpDatagram(IpPacket ipPacket) { var udpDatagram = ipPacket.ToUdpDatagram(); if (udpDatagram == default(UdpDatagram)) { return(default(SnmpDatagram)); } try { SnmpDatagram snmpDatagram; var result = udpDatagram.TryParseSnmpDatagram(out snmpDatagram); if (result) { return(snmpDatagram); } } catch { // Ignored. } return(default(SnmpDatagram)); }
/// <summary> /// Prints the time and length of each received packet /// </summary> private static void device_OnPacketArrival(object sender, CaptureEventArgs e) { DateTime time = e.Packet.Timeval.Date; int len = e.Packet.Data.Length; //Console.WriteLine("{0}:{1}:{2},{3} Len={4}", // time.Hour, time.Minute, time.Second, time.Millisecond, len); //// open the output file //string s = "cap.txt"; //var captureFileWriter = new CaptureFileWriterDevice(e.Device, s); //// write the packet to the file //captureFileWriter.Write(e.Packet); //Console.WriteLine("Packet dumped to file."); var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); //Raw基础包对象 var ipPacket = IpPacket.GetEncapsulated(packet); string srcIp = ipPacket.SourceAddress.ToString(); string dstIp = ipPacket.DestinationAddress.ToString(); if (ipPacket.Protocol == IPProtocolType.TCP) { Console.WriteLine(ipPacket.Protocol.ToString()); var tcpPacket = (TcpPacket)ipPacket.Extract(typeof(TcpPacket)); string srcport = tcpPacket.SourcePort.ToString(); string dstPort = tcpPacket.DestinationPort.ToString(); //if(srcIp == "192.168.1.108") Console.WriteLine(srcIp + ":" + srcport + "\t>\t" + dstIp + ":" + dstPort); } }
// tcp public void VerifyPacket1(Packet p, RawCapture rawCapture) { Console.WriteLine(p.ToString()); EthernetPacket e = (EthernetPacket)p; Assert.AreEqual("0016CFC91E29", e.SourceHwAddress.ToString()); Assert.AreEqual("0014BFF2EF0A", e.DestinationHwAddress.ToString()); IpPacket ip = (IpPacket)p.PayloadPacket; Assert.AreEqual(System.Net.IPAddress.Parse("192.168.1.104"), ip.SourceAddress); Assert.AreEqual(System.Net.IPAddress.Parse("86.42.196.13"), ip.DestinationAddress); Assert.AreEqual(64, ip.TimeToLive); Assert.AreEqual(0x2ff4, ((IPv4Packet)ip).CalculateIPChecksum()); Assert.AreEqual(1171483600, rawCapture.Timeval.Seconds); Assert.AreEqual(125234.000, rawCapture.Timeval.MicroSeconds); TcpPacket tcp = (TcpPacket)ip.PayloadPacket; Assert.AreEqual(56925, tcp.SourcePort); Assert.AreEqual(50199, tcp.DestinationPort); Assert.IsTrue(tcp.Ack); Assert.IsTrue(tcp.Psh); Assert.AreEqual(16666, tcp.WindowSize); Assert.AreEqual(0x9b02, tcp.CalculateTCPChecksum()); Assert.AreEqual(0x9b02, tcp.Checksum); Assert.IsTrue(tcp.ValidTCPChecksum); }
private void AnalyzeTCP(Packet p) { if (!(p.PayloadPacket.PayloadPacket is TcpPacket)) { return; } EthernetPacket ethernet = (EthernetPacket)p; IpPacket ip = (IpPacket)p.PayloadPacket; TcpPacket tcp = (TcpPacket)p.PayloadPacket.PayloadPacket; Neighbor neighbor = null; if (tcp.Syn && tcp.Ack) { neighbor = Program.CurrentProject.data.GetNeighbor(ethernet.SourceHwAddress); if (neighbor == null) { return; } if (neighbor.ExistsIP(ip.SourceAddress)) { Port port = new Port(tcp.SourcePort, Protocol.TCP, ip.SourceAddress); if (!(neighbor.ExistsPort(port))) { neighbor.AddPort(port); Program.CurrentProject.data.AddNeighbor(neighbor); } } else { return; } } }
static void dev_OnPacketArrival(object sender, CaptureEventArgs e) { Packet packet = IpPacket.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); IPv4Packet pv4 = packet.PayloadPacket as IPv4Packet; IPv6Packet pv6 = packet.PayloadPacket as IPv6Packet; if (pv4 != null) { total += pv4.TotalLength; String src = pv4.SourceAddress.ToString(); String dst = pv4.DestinationAddress.ToString(); Console.Out.WriteLine(src + " --> " + dst + "\tlen:" + pv4.TotalLength); } if (pv6 != null) { total += pv6.TotalLength; String src = pv6.SourceAddress.ToString(); String dst = pv6.DestinationAddress.ToString(); Console.Out.WriteLine(src + " --> " + dst + "\tlen:" + pv6.TotalLength); } //Console.Out.WriteLine(total); }
static void device_OnPaketArrival(object sender, CaptureEventArgs e) { Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); if (argLayerType == "l") { printHead(packet.Header); } if (argLayerType == "n") { IpPacket ipPac = packet.Extract(typeof(IpPacket)) as IpPacket; if (ipPac != null) { Console.WriteLine("Ver: {0} ", ipPac.Version); Console.WriteLine("Sadr: {0}", ipPac.SourceAddress); printHead(packet.PayloadPacket.Header); } } if (argLayerType == "t") { var tcpPac = packet.Extract(typeof(TcpPacket)) as TcpPacket; if (tcpPac != null) { printHead(packet.PayloadPacket.PayloadPacket.Header); Console.WriteLine("SPort: {0}", tcpPac.SourcePort); Console.WriteLine("DPort: {0}", tcpPac.DestinationPort); Console.WriteLine("Check: {0}", tcpPac.Checksum); Console.WriteLine("PayData: {0}", Encoding.ASCII.GetString(tcpPac.PayloadData)); } } }
static void localAreaNetworkNIC_OnPacketArrival(object sender, CaptureEventArgs e) { //DateTime time = e.Packet.Timeval.Date; //int len = e.Packet.Data.Length; //string content = ByteArrayToString(e.Packet.Data); //Console.WriteLine("{0}:{1}:{2},{3} Len={4}: {5}", // time.Hour, time.Minute, time.Second, time.Millisecond, len, content); var packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); if (e.Packet.LinkLayerType == LinkLayers.Ethernet) { EthernetPacket ethernetPacket = (EthernetPacket)packet; PhysicalAddress destMacAddress = ethernetPacket.DestinationHwAddress; PhysicalAddress srcMacAddress = ethernetPacket.SourceHwAddress; //Console.WriteLine("Mac: {0} -> {1}", srcMacAddress, destMacAddress); } IpPacket ipPacket = IpPacket.GetEncapsulated(packet); if (ipPacket != null) { IPAddress srcIpAddress = ipPacket.SourceAddress; IPAddress destIpAddress = ipPacket.DestinationAddress; //Console.WriteLine("IP: {0} -> {1}", srcIpAddress, destIpAddress); TcpPacket tcpPacket = TcpPacket.GetEncapsulated(packet); if (tcpPacket != null) { int srcPort = tcpPacket.SourcePort; int destPort = tcpPacket.DestinationPort; //Console.WriteLine("TCP Port: {0} -> {1}", srcPort, destPort); byte[] tcpBody = RipHeader(tcpPacket.Bytes, tcpPacket.Header); string packetString = ByteArrayToString(tcpBody); if (packetString.Contains("HTTP")) { Console.WriteLine("IP: {0} -> {1}", srcIpAddress, destIpAddress); Console.WriteLine("TCP Port: {0} -> {1}", srcPort, destPort); Console.WriteLine(ByteArrayToString(tcpBody)); } } //UdpPacket udpPacket = UdpPacket.GetEncapsulated(packet); //if (udpPacket != null) //{ // int srcPort = udpPacket.SourcePort; // int destPort = udpPacket.DestinationPort; // Console.WriteLine("UDP Port: {0} -> {1}", srcPort, destPort); //} } //string packetString = PacketString(packet); //Console.WriteLine(packetString); //Console.WriteLine(); }
static void Program_OnPacketArrival(object sender, CaptureEventArgs e) { //TimeSpan ts = stopwatch.Elapsed; try { if (TimeSpan.Parse(stopwatch.Elapsed.ToString()).TotalSeconds >= 10) { //ts = TimeSpan.Zero; //stopwatch.Stop(); stopwatch.Reset(); //Ports.Clear(); Process process = Process.GetProcessById(Process.GetProcessesByName("viber")[0].Id); process.Kill(); captureDevice.StopCapture(); //Thread.Sleep(5000); System.Diagnostics.Process MyProc = new System.Diagnostics.Process(); MyProc.StartInfo.FileName = @"C:\Users\pna\AppData\Local\Viber\Viber.exe"; MyProc.Start(); Start(); } } catch { } // парсинг всего пакета Packet packet = Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data); // получение только TCP пакета из всего фрейма var tcpPacket = TcpPacket.GetEncapsulated(packet); // получение только IP пакета из всего фрейма var ipPacket = IpPacket.GetEncapsulated(packet); if (tcpPacket != null && ipPacket != null) { //DateTime time = e.Packet.Timeval.Date; //int len = e.Packet.Data.Length; //// IP адрес отправителя //var srcIp = ipPacket.SourceAddress.ToString(); //// IP адрес получателя //var dstIp = ipPacket.DestinationAddress.ToString(); //// порт отправителя //var srcPort = tcpPacket.SourcePort.ToString(); //// порт получателя //var dstPort = tcpPacket.DestinationPort.ToString(); //// данные пакета //var data = tcpPacket.PayloadPacket; //tcpPacket.DestinationPort.ToString() if (Ports.Any(x => x.num_port.Contains(tcpPacket.DestinationPort.ToString()))) { if (ipPacket.DestinationAddress.ToString() == "192.168.1.28") { stopwatch.Restart(); //stopwatch.Start(); Console.WriteLine("{0}({1}) {2} - {3}", i++, DateTime.Now.ToString(), tcpPacket.DestinationPort.ToString(), e.Packet.Data.Length); //if (total_min >= 45) { //} } } } }
public override string Open() { /*string addr = Common.Conf.IP1 + "." + * Common.Conf.IP2 + "." + * Common.Conf.IP3 + "." + * Common.Conf.IP4;*/ int port = Common.Conf.Port; if (Socket != null) { return(null); } Socket s = null; Socket = null; try { //IPHostEntry ent = Dns.GetHostEntry(addr); byte[] bt = { Common.Conf.IP1, Common.Conf.IP2, Common.Conf.IP3, Common.Conf.IP4 }; IPAddress ipAddress = new IPAddress(bt);// ent.AddressList[0]; EndPoint destination = new IPEndPoint(ipAddress, port); s = new Socket(destination.AddressFamily, SocketType.Dgram, ProtocolType.Udp); s.Bind(new IPEndPoint(IPAddress.Any, port)); s.Connect(destination); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 500000); s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 500000); Destination = destination;//*/ IpPacket p = IpPacket.GetCommand_PowerOnReset(); Send(p, 1000, s); SpectroWizard.gui.MainForm.SetupConnectionIndicator(true); } catch (Exception e) { if (s != null) { try { SpectroWizard.gui.MainForm.SetupConnectionIndicator(false); s.Shutdown(SocketShutdown.Both); } finally { try { s.Close(); } finally { } } } Common.LogNoMsg(e); return(e.Message); } Socket = s; return(null); }
private static IpPacket ExtractIpPacket(Packet packet) { IpPacket ip_packet = (IpPacket)packet.Extract(typeof(IpPacket)); Debug.WriteLineIf((ip_packet != null), "IP packet: " + ip_packet.ToString()); return(ip_packet); }
private static UdpPacket ExtractUdpPacket(IpPacket ip_packet) { UdpPacket udp_packet = (UdpPacket)ip_packet.Extract(typeof(UdpPacket)); Debug.WriteLineIf(udp_packet != null, "UDP packet: " + udp_packet.ToString()); return(udp_packet); }
public PacketWrapper(TcpRecon tcpRecon) { Count = ++CaptureForm.packetCount; ipPacket = tcpRecon.IpPacket; rawCapture = tcpRecon.RawCapture; tcpPacket = tcpRecon.TcpPacket; Msg = tcpRecon.Msg.ToString(); }
public PacketWrapper(int id, RawCapture p) { this.id = id; Packet pac = Packet.ParsePacket(p.LinkLayerType, p.Data); tcpPacket = pac.Extract(typeof(TcpPacket)) as TcpPacket; ipPacket = pac.Extract(typeof(IpPacket)) as IpPacket; }
public Package(IpPacket ipPacket) { this.CreatedTime = DateTime.Now.ToString("HH:mm:ss"); _sourceAdress = ipPacket.SourceAddress.ToString(); _destinationAddress = ipPacket.DestinationAddress.ToString(); _nextHeader = ipPacket.NextHeader.ToString(); _protocol = ipPacket.Protocol; }
private void Receive(IpPacket ipPacket) { var protocol = ipPacket.Protocol; if (protocol != IPProtocolType.TCP) { return; } if (ipPacket.PayloadPacket == null) { return; } var tcpPacket = new TcpPacket(new ByteArraySegment(ipPacket.PayloadPacket.BytesHighPerformance)); var isFirstPacket = tcpPacket.Syn; var sourceIp = new IPAddress(ipPacket.SourceAddress.GetAddressBytes()).ToString(); var destinationIp = new IPAddress(ipPacket.DestinationAddress.GetAddressBytes()).ToString(); var connectionId = new ConnectionId(sourceIp, tcpPacket.SourcePort, destinationIp, tcpPacket.DestinationPort); lock (_lock) { TcpConnection connection; bool isInterestingConnection; if (isFirstPacket) { connection = new TcpConnection(connectionId, tcpPacket.SequenceNumber); OnNewConnection(connection); isInterestingConnection = connection.HasSubscribers; if (!isInterestingConnection) { return; } _connections[connectionId] = connection; Debug.Assert(ipPacket.PayloadPacket.PayloadData.Length == 0); } else { isInterestingConnection = _connections.TryGetValue(connectionId, out connection); if (!isInterestingConnection) { return; } if (!string.IsNullOrEmpty(TcpLogFile)) { File.AppendAllText(TcpLogFile, string.Format("{0} {1}+{4} | {2} {3}+{4} ACK {5} ({6})\r\n", connection.CurrentSequenceNumber, tcpPacket.SequenceNumber, connection.BytesReceived, connection.SequenceNumberToBytesReceived(tcpPacket.SequenceNumber), ipPacket.PayloadLength, tcpPacket.AcknowledgmentNumber, connection.BufferedPacketDescription)); } connection.HandleTcpReceived(tcpPacket.SequenceNumber, new ByteArraySegment(ipPacket.PayloadPacket.PayloadData)); } } }
private bool NeedToRoute(IpPacket pIp) { bool needToRoute = true; foreach (PcapAddress remoteAddress in Device.Addresses) { if (remoteAddress.Addr.ipAddress == null) continue; if (remoteAddress.Addr.ipAddress.Equals(pIp.DestinationAddress)) needToRoute = false; // Va dirigido a nuestra IP, así que no se enruta } return needToRoute; }
/// <summary> /// Initializes a new instance of the <see cref="SnmpTrapV1"/> struct. /// </summary> /// <param name="ipPacket">The ip packet.</param> public SnmpTrapV1(IpPacket ipPacket) : this(ipPacket.PacketData) { }
public PacketWrapper2(RawCapture rawCapture) { rawPacket = rawCapture; Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); ipPacket = IpPacket.GetEncapsulated(packet); tcpPacket = TcpPacket.GetEncapsulated(packet); Count = ++CaptureForm.packetCount; if (ipPacket.SourceAddress.Equals(CaptureForm.MyIp)) { MyPort = tcpPacket.SourcePort; Destination = "sent"; } else { MyPort = tcpPacket.DestinationPort; Destination = "received"; } Flags = "["; if (tcpPacket.Syn) Flags += "SYN"; else if (tcpPacket.Psh) Flags += "PSH"; else if (tcpPacket.Fin) Flags += "FIN"; if (tcpPacket.Ack) { if (Flags.Length > 1) Flags += ","; Flags += "ACK"; } Flags += "]"; Sequence = tcpPacket.SequenceNumber; Acknowledgment = tcpPacket.AcknowledgmentNumber; Len = tcpPacket.PayloadData.Length; Time = rawCapture.Timeval.MicroSeconds; Msg = Encoding.ASCII.GetString(tcpPacket.PayloadData); }
private static void Router_Capture(object arg1, IpPacket arg2) { Console.WriteLine(arg2); }
protected void OnPacketReceived(IpPacket data) { var packetReceived = PacketReceived; packetReceived?.Invoke(data); }
/// <summary> /// Creates a new "Source Quench" ICMP packet. /// </summary> /// <param name="packet">The IP packet in whose response the source /// quench packet is being sent.</param> /// <returns>An initialized instance of the IcmpPacket class representing /// a "Source Quench" ICMP packet.</returns> /// <exception cref="ArgumentNullException">Thrown if the packet parameter /// is null.</exception> public static IcmpPacket SourceQuench(IpPacket packet) { packet.ThrowIfNull("packet"); return new IcmpPacket(IcmpType.SourceQuench, 0, GetIpData(packet)); }
/// <summary> /// Creates a new "Time Exceeded" ICMP packet. /// </summary> /// <param name="packet">The IP packet whose TTL value expired.</param> /// <returns>An initialized instance of the IcmpPacket class representing /// a "TTL expired in transit" ICMP packet.</returns> /// <exception cref="ArgumentNullException">Thrown if the packet parameter /// is null.</exception> public static IcmpPacket TimeExceeded(IpPacket packet) { packet.ThrowIfNull("packet"); return new IcmpPacket(IcmpType.TimeExceed, IcmpCode.TtlExpired, GetIpData(packet)); }
/// <summary> /// The main function of the class receives a tcp packet and reconstructs the stream /// </summary> /// <param name="tcpPacket"></param> public void ReassemblePacket(RawCapture rawCapture) { this.RawCapture = rawCapture; Packet packet = Packet.ParsePacket(rawCapture.LinkLayerType, rawCapture.Data); this.IpPacket = IpPacket.GetEncapsulated(packet); this.TcpPacket = TcpPacket.GetEncapsulated(packet); // if the paylod length is zero bail out //ulong length = (ulong)(tcpPacket.TCPPacketByteLength - tcpPacket.TCPHeaderLength); ulong length = (ulong)(this.TcpPacket.Bytes.Length - this.TcpPacket.Header.Length); if (length == 0) return; reassemble_tcp(length); }
//在树形控件中加入tcp节点 private void tcpTreeView(IpPacket p) { var IPv4 = (IPv4Packet)p.Extract(typeof(IPv4Packet)); if (IPv4 != null) { addIpv4Node(IPv4); } else { var IPv6 = (IPv6Packet)p.Extract(typeof(IPv6Packet)); addIpv6Node(IPv6); } var TCP = (TcpPacket)p.Extract(typeof(TcpPacket)); TreeNode tcpNode = new TreeNode(); tcpNode.Text = "Transmission Control Protocal, Src Port: " + TCP.SourcePort + ", Dst Port: " + TCP.DestinationPort + ", Seq: " + TCP.SequenceNumber.ToString() + ", Ack: " + TCP.Ack.CompareTo(false); treeView.Nodes.Add(tcpNode); tcpNode.Nodes.Add(new TreeNode("Source Port: " + TCP.SourcePort)); tcpNode.Nodes.Add(new TreeNode("Destination Port: " + TCP.DestinationPort)); tcpNode.Nodes.Add(new TreeNode("Sequence number: " + TCP.SequenceNumber)); tcpNode.Nodes.Add(new TreeNode("Acknowledgement: " + TCP.AcknowledgmentNumber)); tcpNode.Nodes.Add(new TreeNode("Header Length: " + (TCP.DataOffset * 4).ToString() + " bytes")); TreeNode allFlags = new TreeNode(); allFlags.Text = System.Convert.ToString(TCP.AllFlags, 2).PadLeft(12, '0') + " = Flags: 0x" + TCP.Header[12].ToString("X").Substring(1, 1).PadLeft(1, '0') + TCP.Header[13].ToString("X").PadLeft(2, '0'); tcpNode.Nodes.Add(allFlags); allFlags.Nodes.Add(new TreeNode("0000 00.. .... = Reserved: Not set")); allFlags.Nodes.Add(new TreeNode(".... .." + TCP.Urg.CompareTo(false) + ". .... = Urgent: " + ((TCP.Urg) ? "Set" : "Not set"))); allFlags.Nodes.Add(new TreeNode(".... ..." + TCP.Ack.CompareTo(false) + " .... = Acknowledgement: " + ((TCP.Ack) ? "Set" : "Not set"))); allFlags.Nodes.Add(new TreeNode(".... .... " + TCP.Psh.CompareTo(false) + "... = Push: " + ((TCP.Psh) ? "Set" : "Not set"))); allFlags.Nodes.Add(new TreeNode(".... .... ." + TCP.Rst.CompareTo(false) + ".. = Reset: " + ((TCP.Rst) ? "Set" : "Not set"))); allFlags.Nodes.Add(new TreeNode(".... .... .." + TCP.Syn.CompareTo(false) + ". = Syn: " + ((TCP.Syn) ? "Set" : "Not set"))); allFlags.Nodes.Add(new TreeNode(".... .... ..." + TCP.Fin.CompareTo(false) + " = Fin: " + ((TCP.Fin) ? "Set" : "Not set"))); tcpNode.Nodes.Add(new TreeNode("Window size value: " + TCP.WindowSize)); tcpNode.Nodes.Add(new TreeNode("Checksum: 0x" + TCP.Checksum.ToString("X4"))); tcpNode.Nodes.Add(new TreeNode("Urgent Pointer: " + TCP.UrgentPointer)); this.treeView.ExpandAll(); }
/// <summary> /// Creates a new "Fragmentation Required" ICMP packet. /// </summary> /// <param name="packet">The IP packet for which fragmentation is /// required.</param> /// <returns>An initialized instance of the IcmpPacket class representing /// a "Fragmentation Required" ICMP packet.</returns> /// <exception cref="ArgumentNullException">Thrown if the packet parameter /// is null.</exception> public static IcmpPacket FragmentationRequired(IpPacket packet) { packet.ThrowIfNull("packet"); return new IcmpPacket(IcmpType.Unreachable, IcmpCode.FragmentationRequired, GetIpData(packet)); }
//在树形控件中加入udp节点 private void udpTreeView(IpPacket p) { var IPv4 = (IPv4Packet)p.Extract(typeof(IPv4Packet)); if (IPv4 != null) { addIpv4Node(IPv4); } else { var IPv6 = (IPv6Packet)p.Extract(typeof(IPv6Packet)); addIpv6Node(IPv6); } var UDP = (UdpPacket)p.Extract(typeof(UdpPacket)); TreeNode udpNode = new TreeNode(); udpNode.Text = "User Datagram Protocal, Src Port: " + UDP.SourcePort + ", Dst Port: " + UDP.DestinationPort; treeView.Nodes.Add(udpNode); udpNode.Nodes.Add(new TreeNode("Source Port: " + UDP.SourcePort)); udpNode.Nodes.Add(new TreeNode("Destination Port: " + UDP.DestinationPort)); udpNode.Nodes.Add(new TreeNode("Length: " + UDP.Length)); udpNode.Nodes.Add(new TreeNode("Checksum: 0x" + UDP.Checksum.ToString("X4"))); this.treeView.ExpandAll(); }
/// <summary> /// Returns the IP header and the first 8 byte of the IP data segment /// as an array of bytes. /// </summary> /// <param name="packet">The IP packet whose data to return.</param> /// <returns>An arry of bytes containing the IP header and the first /// 8 bytes of IP data of the specified IP packet.</returns> /// <exception cref="ArgumentNullException">Thrown if the packet /// parameter is null.</exception> /// <remarks>Many ICMP packets include the IP header and the first 8 /// bytes of data of an IP packet.</remarks> static byte[] GetIpData(IpPacket packet) { packet.ThrowIfNull("packet"); // Many ICMP packets include the 20-byte IP header and the first // 8 bytes of an IP packet. var serialized = packet.Serialize(); var size = Math.Min(20 + 8, serialized.Length); var data = new byte[size]; Array.Copy(serialized, data, data.Length); return data; }
//在树形控件中加入icmp节点 private void icmpTreeView(IpPacket p) { var IPv4 = (IPv4Packet)p.Extract(typeof(IPv4Packet)); if (IPv4 != null) { addIpv4Node(IPv4); } string MF = Convert.ToString(IPv4.FragmentFlags, 2).PadLeft(3, '0').Substring(2, 1); int OFF = IPv4.FragmentOffset; var ICMP = (ICMPv4Packet)p.Extract(typeof(ICMPv4Packet)); TreeNode icmpNode = new TreeNode(); icmpNode.Text = "Internet Control Meaasge Protocal"; treeView.Nodes.Add(icmpNode); string type = ICMP.Header[0].ToString("D"); string code = ICMP.Header[1].ToString("D"); string description = ""; //如果是分片包且不是第一个,输出See it's first fragment if (isFragment(MF, OFF) && OFF != 0) { type = "See it's first fragment"; code = "See it's first fragment"; } else { if (type == "0") description = " (Echo (ping) reply)"; else if (type == "8") description = " (Echo (ping) requst)"; else description = ""; } icmpNode.Nodes.Add(new TreeNode("Type: " + type + description)); icmpNode.Nodes.Add(new TreeNode("Code: " + code)); icmpNode.Nodes.Add(new TreeNode("Checksum: 0x" + ICMP.Checksum.ToString("X4"))); this.treeView.ExpandAll(); }
/// <summary> /// Creates a new "Destination Unreachable" ICMP packet. /// </summary> /// <param name="packet">The IP packet whose destination is /// unreachable.</param> /// <returns>An initialized instance of the IcmpPacket class representing /// a "Destination Network Unreachable" ICMP packet.</returns> /// <exception cref="ArgumentNullException">Thrown if the packet parameter /// is null.</exception> public static IcmpPacket Unreachable(IpPacket packet) { packet.ThrowIfNull("packet"); return new IcmpPacket(IcmpType.Unreachable, IcmpCode.DestinationNetworkUnreachable, GetIpData(packet)); }
//在树形控件中加入igmp节点 private void igmpTreeView(IpPacket p) { var IPv4 = (IPv4Packet)p.Extract(typeof(IPv4Packet)); if (IPv4 != null) { addIpv4Node(IPv4); } var IGMP = (IGMPv2Packet)p.Extract(typeof(IGMPv2Packet)); TreeNode igmpNode = new TreeNode(); igmpNode.Text = "Internet Group Management Protocal"; treeView.Nodes.Add(igmpNode); igmpNode.Nodes.Add(new TreeNode("Type: " + IGMP.Type + " (0x" + IGMP.Header[0].ToString("X2") + ")")); igmpNode.Nodes.Add(new TreeNode("Max Resp Time: " + (Convert.ToDouble(IGMP.MaxResponseTime) / 10.0).ToString("0.0") + " sec" + " (0x" + IGMP.Header[1].ToString("X2") + ")")); igmpNode.Nodes.Add(new TreeNode("Header checksum: 0x" + IGMP.Checksum.ToString("X4"))); igmpNode.Nodes.Add(new TreeNode("Multicast Asddress: " + IGMP.GroupAddress)); this.treeView.ExpandAll(); }