void rec(byte[] data, int length) { IPHeader ipHeader = new IPHeader(data, length); IPacket packet = ipHeader.ParseData(); if (OnPacket != null) { OnPacket(ipHeader.ProtocolType, packet); } if (OnTcpStream != null && ipHeader.ProtocolType == ProtocolType.Tcp) { TcpHeader tcp = (TcpHeader)packet; if (AllowTcpPacket(tcp)) { TcpStream stream = TcpStream.GetStream(_TcpStreams, tcp); if (stream != null) { if (stream.IsClossed) { _TcpStreams.Remove(stream); } OnTcpStream(stream); } } } Receive(); }
//Helper function which returns the information contained in the IP header as a //tree node private TreeNode MakeIPTreeNode(IPHeader ipHeader) { TreeNode ipNode = new TreeNode(string.Format("{0}/IP {1}", ipHeader.ProtocolType, ipHeader.Version)); ipNode.Nodes.Add("Header Length: " + ipHeader.HeaderLength); ipNode.Nodes.Add("Differntiated Services: " + ipHeader.DifferentiatedServices); TreeNode dataNode = new TreeNode("Message/Total Length: " + ipHeader.MessageLength + "/" + ipHeader.TotalLength); //dataNode.ToolTipText = SpecUtil.GetHexViewString(ipHeader.Data); dataNode.ForeColor = System.Drawing.Color.Blue; dataNode.Tag = ipHeader.Data; ipNode.Nodes.Add(dataNode); ipNode.Nodes.Add("Identification: " + ipHeader.Identification); ipNode.Nodes.Add("Flags: " + ipHeader.Flags); ipNode.Nodes.Add("Fragmentation Offset: " + ipHeader.FragmentationOffset); ipNode.Nodes.Add("Time to live: " + ipHeader.TTL); ipNode.Nodes.Add("Checksum: " + ipHeader.Checksum); //ipNode.Nodes.Add("Source: " + ipHeader.SourceAddress.ToString()); //ipNode.Nodes.Add("Destination: " + ipHeader.DestinationAddress.ToString()); return(ipNode); }
public static bool ComputeUDPChecksum(IPHeader ipHeader, UDPHeader udpHeader) { ComputeIPChecksum(ipHeader); int ipData_len = ipHeader.getDataLength(); if (ipData_len < 0) { return(false); } long sum = getsum(ipHeader.mData, ipHeader.mOffset + IPHeader.offset_src_ip, 8); sum += ipHeader.getProtocol() & 0xFF; sum += ipData_len; short oldCrc = udpHeader.getCrc(); udpHeader.setCrc(0); short newCrc = checksum(sum, udpHeader.mData, udpHeader.mOffset, ipData_len); udpHeader.setCrc(newCrc); return(oldCrc == newCrc); }
private void OnReceive(IAsyncResult ar) { if (!isPaused) { try { int length = ipSocket.EndReceive(ar); byte[] packet = new byte[length]; Array.Copy(byteData, 0, packet, 0, length); IPHeader ipHeader = new IPHeader(packet, length); if (ipHeader.SourceAddress.Equals(IPAddress)) { OnPacketSent(ipHeader); } if (ipHeader.DestinationAddress.Equals(IPAddress)) { OnPacketReceived(ipHeader); } } catch (Exception ex) { Sniffer.LogTrace(ex); } finally { byteData = new byte[128]; // set to 16276 bytes // continue receiving ipSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } } }
//Helper function which returns the information contained in the IP header as a //tree node public static TreeNode MakeIPTreeNode(IPHeader ipHeader) { TreeNode ipNode = new TreeNode(); ipNode.Text = "IP"; ipNode.Nodes.Add("Ver: " + ipHeader.Version); ipNode.Nodes.Add("Header Length: " + ipHeader.HeaderLength); ipNode.Nodes.Add("Differntiated Services: " + ipHeader.DifferentiatedServices); ipNode.Nodes.Add("Total Length: " + ipHeader.TotalLength); ipNode.Nodes.Add("Identification: " + ipHeader.Identification); ipNode.Nodes.Add("Flags: " + ipHeader.Flags); ipNode.Nodes.Add("Fragmentation Offset: " + ipHeader.FragmentationOffset); ipNode.Nodes.Add("Time to live: " + ipHeader.TTL); switch (ipHeader.ProtocolType) { case Protocol.TCP: ipNode.Nodes.Add("Protocol: " + "TCP"); break; case Protocol.UDP: ipNode.Nodes.Add("Protocol: " + "UDP"); break; case Protocol.Unknown: ipNode.Nodes.Add("Protocol: " + "Unknown"); break; } ipNode.Nodes.Add("Checksum: " + ipHeader.Checksum); ipNode.Nodes.Add("Source: " + ipHeader.SourceAddress.ToString()); ipNode.Nodes.Add("Destination: " + ipHeader.DestinationAddress.ToString()); return(ipNode); }
/// <summary> /// Função que varre todos os pacotes recebidos em busca de pacotes que /// pertençam a mesma conexão do pacote fornecido /// </summary> /// <param name="InitialPack"></param> public void FindConnectionPacks(IPHeader InitialPack) { if (InitialPack.ProtocolType == Protocol.TCP) { userControlDiagrama1.ClearConnectionData(); TCPHeader th1 = new TCPHeader(InitialPack.Data, InitialPack.MessageLength); string SourceSockIni = InitialPack.SourceAddress.ToString() + ":" + th1.SourcePort; string DestinSockIni = InitialPack.DestinationAddress.ToString() + ":" + th1.DestinationPort; for (int i = 0; i < ListaPacotesRecebidos.Count; i++) { if (ListaPacotesRecebidos[i].ProtocolType == Protocol.TCP) { TCPHeader th2 = new TCPHeader(ListaPacotesRecebidos[i].Data, ListaPacotesRecebidos[i].MessageLength); string SourceSock = ListaPacotesRecebidos[i].SourceAddress.ToString() + ":" + th2.SourcePort; string DestinSock = ListaPacotesRecebidos[i].DestinationAddress.ToString() + ":" + th2.DestinationPort; if ((SourceSock == SourceSockIni && DestinSock == DestinSockIni) || SourceSock == DestinSockIni && DestinSock == SourceSockIni) { userControlDiagrama1.AdicionaFrameTCP(ListaPacotesRecebidos[i]); } } } userControlDiagrama1.Visible = true; } else if (InitialPack.ProtocolType == Protocol.UDP) { MessageBox.Show("O protocolo UDP não é orientado a conexão!"); } }
public void SetData(IPHeader ip, TCPHeader tcp) { label1FlagsIP.Text = ip.Flags; label1OffsetFragmIP.Text = ip.FragmentationOffset; labelCSIP.Text = ip.Checksum; labelCSTCP.Text = tcp.Checksum; labelEndDestIP.Text = ip.DestinationAddress.ToString(); labelEndOrgIP.Text = ip.SourceAddress.ToString(); labelIDIP.Text = ip.Identification; labelIHLIP.Text = "???"; labelFlagsTCP.Text = tcp.Flags; labelJanelaTCP.Text = tcp.WindowSize; labelNroConfirmTCP.Text = tcp.AcknowledgementNumber; labelNroSeqTCP.Text = tcp.SequenceNumber; labelOffsetTCP.Text = "??"; labelPonteiroTCP.Text = tcp.UrgentPointer; labelPortaDestinoTCP.Text = tcp.DestinationPort; labelPortaOrigmTCP.Text = tcp.SourcePort; labelProtocolIP.Text = ip.ProtocolType.ToString(); labelTamanhoTotalIP.Text = ip.TotalLength; labelResTCP.Text = "-"; labelTipoServicoIP.Text = "?"; labelTTLIP.Text = ip.TTL; labelVersaoIP.Text = ip.Version; }
private void ParseHeader(RawDGram p, int len) { Console.WriteLine("Parsing Header"); IPHeader header = new IPHeader(p.rawBytes, len); switch (header.ProtocolType) { case Protocol.ICMP: ICMPHeader icmpHeader = new ICMPHeader(header.Data, header.MessageLength); //Console.WriteLine(String.Format("ICMP type: {0} code: {1}", icmpHeader.Type, icmpHeader.Code)); if (icmpHeader.Type == ICMPHeader.ICMPTypes.DestinationUnreachable && icmpHeader.Code == 3) { //Binary search the MTU (this is used during the probe phase of some congestion control //algorithms. Also, the initial congestion window should be calculated in terms of bytes i.e. (mtu/windowsize = packets) } break; case Protocol.TCP: //Console.WriteLine("TCP packet received"); break; case Protocol.UDP: UDPHeader udpHeader = new UDPHeader(header.Data, header.MessageLength); HandleUDP(header, udpHeader); break; case Protocol.Unknown: //Console.WriteLine("Unknown packet received"); break; default: throw new ArgumentOutOfRangeException(); } }
public void Start() { using (FileStream stream = new FileStream("D:\\work\\Snipper.txt", FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(stream)) { while (true) { int nReceived = base.Receive(byteData, SocketFlags.None); IPHeader ipheader = new IPHeader(byteData, nReceived); sw.WriteLine("-----------------------------------------------------------------------------------"); sw.Write(ipheader.ToString()); sw.WriteLine(); switch (ipheader.ProtocolType) { case 6: TCPHeader tcpHeader = new TCPHeader(ipheader.Data, ipheader.MessageLength); Console.WriteLine(ipheader.SourceAddress.ToString() + "-" + ipheader.DestinationAddress.ToString()); sw.Write(tcpHeader.ToString()); break; case 7: UDPHeader udpHeader = new UDPHeader(ipheader.Data, ipheader.MessageLength); Console.WriteLine(ipheader.SourceAddress.ToString() + "-" + ipheader.DestinationAddress.ToString()); sw.Write(udpHeader.ToString()); break; } sw.WriteLine("-----------------------------------------------------------------------------------"); sw.WriteLine(); sw.Flush(); } } } }
private void ParseTcpIPData(byte[] byteData, int nReceived) { //Since all protocol packets are encapsulated in the IP datagram //so we start by parsing the IP header and see what protocol data //is being carried by it and filter source and destination address. IPHeader ipHeader = new IPHeader(byteData, nReceived); if (ipHeader.SourceAddress.ToString().Equals(TcpClient.Address) || ipHeader.DestinationAddress.ToString().Equals(TcpClient.Address)) { //Now according to the protocol being carried by the IP datagram we parse //the data field of the datagram if it carries TCP protocol if ((ipHeader.ProtocolType == Protocol.TCP) && (ipHeader.MessageLength > 0)) { TCPHeader tcpHeader = new TCPHeader(ipHeader.Data, ipHeader.MessageLength); //Now filter only on our Denon (or Marantz) receiver if (tcpHeader.SourcePort == TcpClient.Port.ToString() || tcpHeader.DestinationPort == TcpClient.Port.ToString()) { if (tcpHeader.MessageLength > 1) { ParseAvrData(tcpHeader.Data, tcpHeader.MessageLength); } } } } }
private void ParseData(byte[] byteData, int nReceived) { IPHeader ipHeader = new IPHeader(byteData, nReceived); switch (ipHeader.ProtocolType) { case Protocol.TCP: TCPHeader tcpHeader = new TCPHeader(ipHeader.Data, ipHeader.MessageLength); //Length of the data field if (tcpHeader.SourcePort == "4988") { lock (((ICollection)_queue).SyncRoot) { _queue.Enqueue(byteData); _syncEvents.NewItemEvent.Set(); } } break; case Protocol.UDP: break; case Protocol.Unknown: break; } }
private void DecodePacket() { // Since all protocol packets are encapsulated in the IP datagram // so we start by parsing the IP header and see what protocol data // is being carried by it IPHeader = new IPHeader(m_packet, m_dataLength); ProtocolHeader = ProtocolFactory.Factory(IPHeader.ProtocolType, IPHeader.DataGram, IPHeader.MessageLength); }
public UDPHeader(IPAddress sourceAddress, IPAddress destinationAddress, ushort sourcePort, ushort destinationPort, int dataLength) { unsafe { IPHeader = new IPHeader(sourceAddress, destinationAddress, dataLength + sizeof(UDPHeader)); } SourcePort = (ushort)IPAddress.HostToNetworkOrder((short)sourcePort); DestinationPort = (ushort)IPAddress.HostToNetworkOrder((short)destinationPort); Length = (ushort)IPAddress.HostToNetworkOrder((short)(dataLength + 8)); Checksum = 0; }
private void ParseData(byte[] byteData, int nReceived) { try { //Since all protocol packets are encapsulated in the IP datagram //so we start by parsing the IP header and see what protocol data //is being carried by it IPHeader ipHeader = new IPHeader(byteData, nReceived); //Now according to the protocol being carried by the IP datagram we parse //the data field of the datagram switch (ipHeader.ProtocolType) { case pinger_csharp.Protocol.TCP: TCPHeader tcpHeader = new TCPHeader(ipHeader.Data, //IPHeader.Data stores the data being //carried by the IP datagram ipHeader.MessageLength); //Length of the data field //If the port is equal to 53 then the underlying protocol is DNS //Note: DNS can use either TCP or UDP thats why the check is done twice if (tcpHeader.DestinationPort == "53" || tcpHeader.SourcePort == "53") { } newPacketParse(new Packet(ipHeader, tcpHeader)); break; case pinger_csharp.Protocol.UDP: UDPHeader udpHeader = new UDPHeader(ipHeader.Data, //IPHeader.Data stores the data being //carried by the IP datagram (int)ipHeader.MessageLength); //Length of the data field //If the port is equal to 53 then the underlying protocol is DNS //Note: DNS can use either TCP or UDP thats why the check is done twice if (udpHeader.DestinationPort == "53" || udpHeader.SourcePort == "53") { //Length of UDP header is always eight bytes so we subtract that out of the total //length to find the length of the data } newPacketParse(new Packet(ipHeader, udpHeader)); break; case pinger_csharp.Protocol.Unknown: break; //Thread safe adding of the packets!! } } catch (Exception ex) { MessageBox.Show(ex.Message, "parseData", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void agent_Trace(object sender, EventArgs e) { IPHeader tls = (IPHeader)sender; //Console.WriteLine("{0} {1} {2} {3}", tls.TlsHeader.ContentType, tls.TlsHeader.MajorVersion, tls.TlsHeader.MinorVersion, tls.TlsHeader.Length); for (int i = 0; i < int.Parse(tls.TotalLength); i++) { Console.Write("{0:X}", tls.Data[i]); } Console.WriteLine(); }
/// <summary> /// Handles the specific UDP sockets /// </summary> /// <param name="ipHeader">The IP Header</param> /// <param name="udpHeader">The UDP Header</param> private void HandleUDP(IPHeader ipHeader, UDPHeader udpHeader) { //todo: add a checksum verification //Console.WriteLine("UDP Packet Received"); EncryptedPacket p = new EncryptedPacket(mtu); p.rawBytes = udpHeader.Data; p.sender = new IPEndPoint(ipHeader.SourceAddress, udpHeader.DestinationPort); p.UnpackHeader(); base.HandlePacket(p); }
public static bool ComputeIPChecksum(IPHeader ipHeader) { short oldCrc = ipHeader.getCrc(); ipHeader.setCrc(0); short newCrc = checksum(0, ipHeader.mData, ipHeader.mOffset, ipHeader.getHeaderLength()); ipHeader.setCrc(newCrc); return(oldCrc == newCrc); }
private void OnPacketSent(IPHeader ipHeader) { if (IpPacketSent != null) { IpPacketSent(ipHeader, EventArgs.Empty); } TCPHeader tcpHeader = new TCPHeader(ipHeader.Data, ipHeader.MessageLength); if (TcpPacketSent != null) { TcpPacketSent(tcpHeader, EventArgs.Empty); } }
/// <summary> /// Função que recebe um array de bytes contendo as informações do frame e monta o frame com estes dados. /// Após a montagem deste frame, o mesmo é armazenado na lista de pacotes recebidos. /// </summary> /// <param name="byteData"></param> /// <param name="nReceived"></param> private void ParseData(byte[] byteData, int nReceived) { //Since all protocol packets are encapsulated in the IP datagram //so we start by parsing the IP header and see what protocol data //is being carried by it IPHeader ipHeader = new IPHeader(byteData, nReceived); ipHeader.ListIndex = ListaPacotesRecebidos.Count; ListaPacotesRecebidos.Add(ipHeader); AddFrame addFrame = new AddFrame(OnAddFrame); //Thread safe adding of the nodes panel1.Invoke(addFrame, new object[] { ipHeader }); }
public static ushort SumPseudoHeader(IPHeader !ipHeader) { uint sum = 0; uint origin = (uint)ipHeader.srcAddr; uint target = (uint)ipHeader.destAddr; sum = (origin & 0xffff) + ((origin >> 16) & 0xffff); sum += (target & 0xffff) + ((target >> 16) & 0xffff); sum += ipHeader.protocol; sum += (ipHeader.totalLength - (ipHeader.verLen & 0xfu) * 4u); // Double-wrap the sum sum = (sum & 0xFFFF) + (sum >> 16); sum = (sum & 0xFFFF) + (sum >> 16); return((ushort)sum); }
public override void OnPacket(RichTextBox rtfedit, IPHeader ipHdr, TCPHeader tcpHdr, UDPHeader udpHdr) { ushort datalen = 0; Font savefont = new Font(rtfedit.SelectionFont, FontStyle.Regular); Font ipfont = new Font(savefont, FontStyle.Underline | FontStyle.Bold); // rtfedit.SelectionFont = ipfont; //rtfedit.SelectionColor = Color.Cyan; //rtfedit.AppendText(String.Format("{0,5} ", ipHdr.Protocol.ToString())); if (tcpHdr != null) { byte[] data = (tcpHdr == null) ? udpHdr.Data : tcpHdr.Data; datalen = (ushort)((data == null) ? 0 : data.Length); if (datalen != 0) { return; } rtfedit.SelectionColor = Color.Cyan; rtfedit.AppendText(String.Format("{0,-8} ", recvnum++)); ushort srcport = (tcpHdr == null) ? udpHdr.SourcePort : tcpHdr.SourcePort; ushort destport = (tcpHdr == null) ? udpHdr.DestinationPort : tcpHdr.DestinationPort; // rtfedit.SelectionColor = Color.Green; rtfedit.AppendText(String.Format("[{0,-15}:{1,-5}]", ipHdr.SourceAddress, srcport)); // rtfedit.SelectionFont = ipfont; rtfedit.SelectionColor = Color.Blue; rtfedit.AppendText(String.Format(" [{0,-15}:{1,-5}]", ipHdr.DestinationAddress, destport)); // rtfedit.SelectionColor = Color.DarkOrange; rtfedit.AppendText(String.Format(" [{0,-3}]\r\n", tcpHdr.FlagsString)); return; } }
private void ParseData(byte[] byteData, int nReceived) { //Since all protocol packets are encapsulated in the IP datagram //so we start by parsing the IP header and see what protocol data //is being carried by it IPHeader ipHeader = new IPHeader(byteData, nReceived); if (ipHeader.uiSourceIPAddress == ipHeader.uiDestinationIPAddress) { MessageBox.Show("Supicious?"); } bool outgoing; var ip = (outgoing = ipHeader.uiSourceIPAddress == IP32) ? ipHeader.uiDestinationIPAddress : ipHeader.uiSourceIPAddress; SniffUnit unit; int unitIdx; if (!sniffIdxs.TryGetValue(ip, out unitIdx)) { unit = new SniffUnit() { target = new IPAddress(ip) }; sniffIdxs[ip] = sniffed.Count; sniffed.Add(unit); unit.LookupServer(); } else { unit = sniffed[unitIdx]; } if (outgoing) { unit.outgoing++; } else { unit.ingoing++; } unit.sizedata += ipHeader.usTotalLength; unit.lastgoing = DateTime.Now; }
static void Main(string[] args) { Console.CancelKeyPress += delegate { _running = false; }; // open handle using (var handle = Diversion.WinDivertOpen("true", WinDivertLayer.Network, 100, 0)) { if (handle.IsInvalid) { Console.WriteLine("Unable to open handle. Error: " + Marshal.GetLastWin32Error()); return; } // prepare headers var ipHeader = new IPHeader(); var ipv6Header = new IPv6Header(); var icmpHeader = new ICMPHeader(); var icmpv6Header = new ICMPv6Header(); var tcpHeader = new TCPHeader(); var udpHeader = new UDPHeader(); var address = new Address(); byte[] buffer = new byte[65535]; uint receiveLength = 0; uint sendLength = 0; string processName; uint pid = 0; // loop while (_running) { pid = 0; } receiveLength = 0; sendLength = 0; fixed(byte *data = buffer) { Diversion.WinDivertHelperParsePacket(data, receiveLength, ipHeader, ipv6Header, icmpHeader, icmpv6Header, tcpHeader, udpHeader, null, null); } } }
static void Main(string[] args) { var pcap = new Pcap(); pcap.Open(ConfigurationManager.AppSettings["Adapter"]); var address = IPAddress.Parse(ConfigurationManager.AppSettings["Address"]); var port = UInt16.Parse(ConfigurationManager.AppSettings["Port"]); Packet packet = null; long tx = 0, rx = 0; while (true) { if ((packet = pcap.Next()) != null) { var eth = new EthernetHeader(packet.Data); if (eth.Protocol == (int)EthernetProtocol.IP) { var ip = new IPHeader(eth); if (ip.Protocol == IPProtocol.Tcp) { var tcp = new TcpHeader(ip); if (ip.SourceIp.Equals(address) && tcp.SourcePort == port) { rx += tcp.Length; } else if (ip.DestinationIp.Equals(address) && tcp.DestinationPort == port) { tx += tcp.Length; } } } } if (KeyPressed()) { Console.WriteLine("{0},{1}", tx, rx); tx = 0; rx = 0; } } }
public void SetIPData(IPHeader iph) { IPData = iph; SourceAdd = IPData.SourceAddress.ToString(); DestAdd = IPData.DestinationAddress.ToString(); labelIndex.Text = iph.ListIndex.ToString(); switch (iph.ProtocolType) { case Protocol.TCP: labelProtocol.Text = "TCP"; TCPData = new TCPHeader(IPData.Data, IPData.MessageLength); SourcePort = TCPData.SourcePort; DestPort = TCPData.DestinationPort; //If the port is equal to 53 then the underlying protocol is DNS //Note: DNS can use either TCP or UDP thats why the check is done twice if (TCPData.DestinationPort == "53" || TCPData.SourcePort == "53") { //TreeNode dnsNode = MakeDNSTreeNode(tcpHeader.Data, (int)tcpHeader.MessageLength); } break; case Protocol.UDP: labelProtocol.Text = "UDP"; UDPData = new UDPHeader(IPData.Data, (int)IPData.MessageLength); SourcePort = UDPData.SourcePort; DestPort = UDPData.DestinationPort; //If the port is equal to 53 then the underlying protocol is DNS //Note: DNS can use either TCP or UDP thats why the check is done twice if (UDPData.DestinationPort == "53" || UDPData.SourcePort == "53") { //TreeNode dnsNode = MakeDNSTreeNode(udpHeader.Data, Convert.ToInt32(udpHeader.Length) - 8); } break; case Protocol.Unknown: break; default: break; } labelSource.Text = SourceAdd + ":" + SourcePort; labelDestination.Text = DestAdd + ":" + DestPort; }
internal static IPpacket CreateIPpacket(IPHeader ipHeader) { IPpacket ip = new IPpacket(); ip.DesIP = ipHeader.DestinationAddress.ToString(); ip.Flags = ipHeader.Flags_con; ip.FragmentationOffset = ipHeader.FragmentationOffset; ip.HeaderLength = ipHeader.HeaderLength; ip.Identification = ipHeader.Identification; ip.Protocol = ipHeader.ProtocolString; ip.SrcIP = ipHeader.SourceAddress.ToString(); ip.Tos = ipHeader.DifferentiatedServices_con; ip.TotalLength = ipHeader.TotalLength; ip.Ttl = ipHeader.TTL; ip.Version = ipHeader.Version_con; ip.HeaderLength = ipHeader.HeaderLength; ip.MessageLength = ipHeader.MessageLength.ToString(); return(ip); }
public void SetData(IPHeader ip, UDPHeader udp) { label1FlagsIP.Text = ip.Flags; label1OffsetFragmIP.Text = ip.FragmentationOffset; labelCSIP.Text = ip.Checksum; labelCSUDP.Text = udp.Checksum; labelEndDestIP.Text = ip.DestinationAddress.ToString(); labelEndOrgIP.Text = ip.SourceAddress.ToString(); labelIDIP.Text = ip.Identification; labelIHLIP.Text = "???"; labelPortaDestinoUDP.Text = udp.DestinationPort; labelPortaOrigmUDP.Text = udp.SourcePort; labelProtocolIP.Text = ip.ProtocolType.ToString(); labelTamanhoTotalIP.Text = ip.TotalLength; labelTamanhoUDP.Text = udp.Length; labelTipoServicoIP.Text = "?"; labelTTLIP.Text = ip.TTL; labelVersaoIP.Text = ip.Version; }
private void OnPacketSync(IAsyncResult ars) { if (m_socket == null) { return; } Socket s = m_socket; int nbytes = s.EndReceive(ars); if (nbytes > 0) { IPHeader ipHdr = new IPHeader(m_buffer, nbytes); TCPHeader tcpHdr = null; UDPHeader udpHdr = null; if (ipHdr.Protocol == ProtocolType.Tcp) { tcpHdr = new TCPHeader(ipHdr.Data, ipHdr.MessageLength); } else if (ipHdr.Protocol == ProtocolType.Udp) { udpHdr = new UDPHeader(ipHdr.Data, ipHdr.MessageLength); } else { //todo } if (CheckWithFilter(ipHdr, tcpHdr, udpHdr)) { if (m_parser != null) { m_parser.OnPacket(richTextBox1, ipHdr, tcpHdr, udpHdr); } } s.BeginReceive(m_buffer, 0, m_buffer.Length, 0, new AsyncCallback(OnPacket), null); } else { richTextBox1.AppendText("Socket出错"); } }
// writes an IP header to a packet // return the next place to write to, fixes the checksum field public static int WriteIPHeader(byte[] !pkt, int offset, IPHeader !hdr) { // check we have enough packet space if (pkt.Length - offset < Size) { return(offset); } int o = offset; pkt[o++] = hdr.verLen; pkt[o++] = hdr.tos; pkt[o++] = (byte)(((ushort)hdr.totalLength) >> 8); pkt[o++] = (byte)(((ushort)hdr.totalLength) & 0xff); pkt[o++] = (byte)(((ushort)hdr.id) >> 8); pkt[o++] = (byte)(((ushort)hdr.id) & 0xff); pkt[o++] = (byte)(((ushort)hdr.offset) >> 8); pkt[o++] = (byte)(((ushort)hdr.offset) & 0xff); pkt[o++] = hdr.ttl; pkt[o++] = hdr.protocol; pkt[o++] = 0; pkt[o++] = 0; // set the ip addresses hdr.srcAddr.CopyOut(pkt, o); o += IPv4.Length; hdr.destAddr.CopyOut(pkt, o); o += IPv4.Length; // calculate checksum ushort chk = IPFormat.FixZeroChecksum(Checksum(pkt, offset, Size)); pkt[offset + 10] = (byte)(((ushort)chk) >> 8); pkt[offset + 11] = (byte)(((ushort)chk) & 0xff); // save the header checksum hdr.checksum = chk; return(o); }
/// <summary> /// 抓包 /// </summary> /// <param name="s"></param> private void CatchPacket(Object s) { Socket ss = s as Socket;//参数转换 byte[] buffer = new byte[2400];//接收数据的缓冲区 while (true) { if (count > 80000) break; int j = ss.Receive(buffer);//接收数据 if (j > 0)//若接收到数据包 { IPHeader ipheader = new IPHeader(buffer, j); ListViewItem lv = new ListViewItem();//定义一个视图项 count += j;//count用于统计接收的总字节数 lv.Text = ipheader.srcAddr.ToString();//往视图项添加源IP lv.SubItems.Add(ipheader.destAddr.ToString());//往视图项添加目的IP if (ipheader.protocol == 6)//6代表TCP { byte[] tcp = new byte[ipheader.length - ipheader.IPlength]; Array.Copy(buffer, ipheader.IPlength, tcp, 0, j - ipheader.IPlength); TcpHeader tcpHeader = new TcpHeader(tcp, j);//解析TCP报文 lv.SubItems.Add(tcpHeader.sourcePort.ToString()); lv.SubItems.Add(tcpHeader.destinationPort.ToString()); lv.SubItems.Add("TCP"); ListViewItem tcpListView = new ListViewItem(); tcpListView.Text = tcpHeader.sourcePort.ToString(); tcpListView.SubItems.Add(tcpHeader.destinationPort.ToString()); tcpListView.SubItems.Add(tcpHeader.seq.ToString()); tcpListView.SubItems.Add(tcpHeader.ack.ToString()); tcpListView.SubItems.Add(tcpHeader.dataOffset.ToString()); tcpListView.SubItems.Add(tcpHeader.win.ToString()); this.listView2.Items.Add(tcpListView); // if (tcpHeader.destinationPort == 80) // { string str = Encoding.UTF8.GetString(buffer,40,j-40); this.richTextBox1.AppendText("\r\n" + str); // } } else if (ipheader.protocol == 17) {//17代表UDP报文 byte[] udp = new byte[ipheader.length - ipheader.IPlength]; Array.Copy(buffer, ipheader.IPlength, udp, 0, j - ipheader.IPlength); UdpHeader udpHeader = new UdpHeader(udp, j);//解析UDP报文 lv.SubItems.Add(udpHeader.sourcePort.ToString()); lv.SubItems.Add(udpHeader.destinationPort.ToString()); lv.SubItems.Add("UDP"); } else {//其他协议 lv.SubItems.Add(" "); lv.SubItems.Add(" "); lv.SubItems.Add("Others"); } lv.SubItems.Add((ipheader.length).ToString()); lv.SubItems.Add(count.ToString()); this.listView1.Items.Add(lv); } } }
static void Main(string[] args) { // This is not really like the netdump example in the native WinDivert examples. Since we are // pulling the names of processes behind packet flows, we need to fully intercept/divert packets, // make the process query, then reinject. If we just sniff, the process will either be closed or // no longer bound to the local port the packet is associated with, and the process query will // be hit or miss (probably fail). So, by fully diverting rather than sniffing, we force // the process to hang open waiting for the packet while we check the process identity, then // hand the packet over untouched. // // Ideally you do not want to be querying the process on every single packet. Rather, you would // create a stucture that keeps track of a network flow, identify the process (protocol, whatever // else) one time, then only re-check when the flow has ended and a new flow has begun. This is // just for basic demonstration though, so we don't create and track any flows. // // Note also that the process identification is still not 100%. Many system processes run under // PID 4. I'm not satisfied with just getting SYSTEM for these processes, and I'd like to // ideally be able to identify exactly which processes they are. Still working on that. Console.WindowWidth = Console.LargestWindowWidth; bool running = true; Console.CancelKeyPress += delegate { running = false; }; Diversion diversion; string filter = "true"; try { diversion = Diversion.Open(filter, DivertLayer.Network, 100, 0); } catch(Exception e) { Console.WriteLine(e.Message); return; } if(!diversion.Handle.Valid) { Console.WriteLine("Failed to open divert handle with error {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error()); return; } IPHeader ipHeader = new IPHeader(); IPv6Header ipv6Header = new IPv6Header(); ICMPHeader icmpHeader = new ICMPHeader(); ICMPv6Header icmpv6Header = new ICMPv6Header(); TCPHeader tcpHeader = new TCPHeader(); UDPHeader udpHeader = new UDPHeader(); Address address = new Address(); byte[] buffer = new byte[65535]; uint receiveLength = 0; uint sendLength = 0; string processName; uint pid = 0; while (running) { pid = 0; receiveLength = 0; sendLength = 0; if (!diversion.Receive(buffer, address, ref receiveLength)) { Console.WriteLine("Failed to receive packet with error {0}", System.Runtime.InteropServices.Marshal.GetLastWin32Error()); continue; } diversion.ParsePacket(buffer, receiveLength, ipHeader, ipv6Header, icmpHeader, icmpv6Header, tcpHeader, udpHeader); if (ipHeader.Valid && tcpHeader.Valid) { Diversion.GetPacketProcess(address, tcpHeader, ipHeader, ref pid, out processName); if (processName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("ERROR {0} and PID is {1}", System.Runtime.InteropServices.Marshal.GetLastWin32Error(), pid); } Console.WriteLine( "{0} IPv4 TCP packet captured destined for {1}:{2} from {3}:{4} {5}.", address.Direction == DivertDirection.Inbound ? "Inbound" : "Outbound", ipHeader.DestinationAddress.ToString(), tcpHeader.DestinationPort.ToString(), ipHeader.SourceAddress.ToString(), tcpHeader.SourcePort.ToString(), address.Direction == DivertDirection.Inbound ? string.Format("to process {0}", processName) : string.Format("from process {0}", processName) ); Console.WriteLine(string.Format("ack: {0}, syn: {1}, len: {2}, seq: {3}", tcpHeader.Ack, tcpHeader.Syn, ipHeader.Length, tcpHeader.SequenceNumber)); } else if(ipHeader.Valid && udpHeader.Valid) { Diversion.GetPacketProcess(address, udpHeader, ipHeader, ref pid, out processName); if (processName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("ERROR {0} and PID is {1}", System.Runtime.InteropServices.Marshal.GetLastWin32Error(), pid); } Console.WriteLine( "{0} IPv4 UDP packet captured destined for {1}:{2} from {3}:{4} {5}.", address.Direction == DivertDirection.Inbound ? "Inbound" : "Outbound", ipHeader.DestinationAddress.ToString(), tcpHeader.DestinationPort.ToString(), ipHeader.SourceAddress.ToString(), tcpHeader.SourcePort.ToString(), address.Direction == DivertDirection.Inbound ? string.Format("to process {0}", processName) : string.Format("from process {0}", processName) ); } else if(ipv6Header.Valid && tcpHeader.Valid) { Diversion.GetPacketProcess(address, tcpHeader, ipv6Header, ref pid, out processName); if (processName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("ERROR {0} and PID is {1}", System.Runtime.InteropServices.Marshal.GetLastWin32Error(), pid); } Console.WriteLine( "{0} IPv6 TCP packet captured destined for {1}:{2} from {3}:{4} {5}.", address.Direction == DivertDirection.Inbound ? "Inbound" : "Outbound", ipHeader.DestinationAddress.ToString(), tcpHeader.DestinationPort.ToString(), ipHeader.SourceAddress.ToString(), tcpHeader.SourcePort.ToString(), address.Direction == DivertDirection.Inbound ? string.Format("to process {0}", processName) : string.Format("from process {0}", processName) ); Console.WriteLine(string.Format("ack: {0}, syn: {1}, len: {2}, seq: {3}", tcpHeader.Ack, tcpHeader.Syn, ipv6Header.Length, tcpHeader.SequenceNumber)); } else if (ipv6Header.Valid && udpHeader.Valid) { Diversion.GetPacketProcess(address, udpHeader, ipv6Header, ref pid, out processName); if (processName.Equals("SYSTEM", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("ERROR {0} and PID is {1}", System.Runtime.InteropServices.Marshal.GetLastWin32Error(), pid); } Console.WriteLine( "{0} IPv6 UDP packet captured destined for {1}:{2} from {3}:{4} {5}.", address.Direction == DivertDirection.Inbound ? "Inbound" : "Outbound", ipHeader.DestinationAddress.ToString(), tcpHeader.DestinationPort.ToString(), ipHeader.SourceAddress.ToString(), tcpHeader.SourcePort.ToString(), address.Direction == DivertDirection.Inbound ? string.Format("to process {0}", processName) : string.Format("from process {0}", processName) ); } if(address.Direction == DivertDirection.Outbound) { diversion.CalculateChecksums(buffer, receiveLength, 0); } diversion.SendAsync(buffer, receiveLength, address, ref sendLength); } diversion.Close(); }
public void AdicionaFrameTCP(IPHeader iph) { IPData = iph; switch (iph.ProtocolType) { case Protocol.TCP: TCPData = new TCPHeader(IPData.Data, IPData.MessageLength); if (labelIPEsquerda.Text == "") { labelIPEsquerda.Text = IPData.SourceAddress + ":" + TCPData.SourcePort; labellabelIPDireita.Text = IPData.DestinationAddress + ":" + TCPData.DestinationPort; } //FrameTCP.Flags = "SYN"; UserControlFrame u = new UserControlFrame(TCPData, iph.ListIndex); u.Location = new Point(0, panel1.Controls.Count * u.Height); ToolTip t = new ToolTip(); t.SetToolTip(u, "Ola, este é o dado Recebido..."); panel1.Controls.Add(u); if (labelIPEsquerda.Text == IPData.SourceAddress + ":" + TCPData.SourcePort) { u.SetDirection(0); } else { u.SetDirection(1); } break; case Protocol.UDP: break; case Protocol.Unknown: break; default: break; } }