private void ReceiveCallback(IAsyncResult ar) { var currentTime = _pingStopwatch.ElapsedTicks; var elapsedTime = 0; var bytesRead = _socket.EndReceive(ar); if (ar.AsyncState is byte[] buffer) { var ipHeader = new IpHeader(buffer, bytesRead); if (ipHeader.ProtocolType == ProtocolType.Icmp && !_receivedIps.ContainsKey(ipHeader.RawSourceAddress)) { UpdateLastResult(); _receivedIps[ipHeader.RawSourceAddress] = true; var icParsed = new IcmpPacket(ipHeader.Data, ipHeader.MessageLength); if (MeasureTime) { // ReSharper disable once AssignNullToNotNullAttribute var parsedTime = BitConverter.ToInt64(icParsed.Data.Array, icParsed.Data.Offset); elapsedTime = TimeSpan.FromTicks(currentTime - parsedTime).Milliseconds; } var pingReplyObject = TypeHelper.Construct <PingReply>(buffer, bytesRead, ipHeader.SourceAddress, elapsedTime); var pingCompletedArgs = TypeHelper.Construct <PingCompletedEventArgs>(pingReplyObject, new Exception(), false, this); OnResult?.Invoke(this, pingCompletedArgs); } } }
/// <summary> /// Invoked when IP data is being delivered through the specified interface. /// </summary> /// <param name="ifc">The interface through which the data was received.</param> /// <param name="data">A sequence of bytes received.</param> /// <exception cref="ArgumentNullException">Thrown if either argument /// is null.</exception> void OnIpInput(Interface ifc, byte[] data) { ifc.ThrowIfNull("ifc"); data.ThrowIfNull("data"); WriteLine(ifc.FullName + " has received new IP packet."); try { var packet = IpPacket.Deserialize(data); // This method is called in "interrupt context" and can execute // on behalf of different NIC's simultaneously. The IP stack // is usually single threaded however, so incoming packets are queued // globally and processed sequentially. if (inputQueue.Count == 0) { Simulation.Callback(nodalProcessingDelay, ProcessPackets); } try { // Enqueue the packet and the interface through which it was // received. inputQueue.Enqueue(new Tuple <IpPacket, Interface>(packet, ifc)); } catch (InvalidOperationException) { // If the host's input queue is full, we must drop the packet. WriteLine("IP input queue overflow, dropping packet."); // Send a "Source Quench" ICMP to the packet's originator. SendIcmp(ifc, packet.Source, IcmpPacket.SourceQuench(packet)); } } catch (SerializationException) { WriteLine(ifc.FullName + " has detected a bad checksum, " + "discarding IP packet."); } }
// Move contents of packet to a byte array (buffer). pingDataSize defines how large // packet.data is. private void Serialize(IcmpPacket packet, Byte[] buffer, Int32 pingDataSize) { buffer[0] = packet.type; buffer[1] = packet.subCode; Array.Copy(BitConverter.GetBytes(packet.checkSum), 0, buffer, 2, 2); Array.Copy(BitConverter.GetBytes(packet.identifier), 0, buffer, 4, 2); Array.Copy(BitConverter.GetBytes(packet.sequenceNumber), 0, buffer, 6, 2); Array.Copy(packet.data, 0, buffer, 8, pingDataSize); }
/// <summary> /// Sends the specified ICMP packet to the specified destination host. /// </summary> /// <param name="ifc">The interface through which the ICMP packet /// should be sent.</param> /// <param name="destination">The IP address of the destination host /// of the ICMP packet.</param> /// <param name="packet">The ICMP packet to send.</param> /// <exception cref="ArgumentNullException">Thrown if any of the arguments /// is null.</exception> void SendIcmp(Interface ifc, IpAddress destination, IcmpPacket packet) { ifc.ThrowIfNull("ifc"); destination.ThrowIfNull("destination"); packet.ThrowIfNull("packet"); Simulation.WriteLine(OutputLevel.Icmp, ifc.FullName + " is queueing a " + packet.Type + " ICMP packet to " + destination, ConsoleColor.Magenta); Output(ifc, destination, packet.Serialize(), IpProtocol.Icmp); }
/// <summary> /// This method get the Packet and calculates the total size /// of the Pack by converting it to byte array /// </summary> private static Int32 Serialize(IcmpPacket packet, Byte[] Buffer, Int32 PacketSize, Int32 PingData) { Int32 cbReturn = 0; // serialize the struct into the array int Index = 0; Byte[] b_type = new Byte[1]; b_type[0] = (packet.Type); Byte[] b_code = new Byte[1]; b_code[0] = (packet.SubCode); Byte[] b_cksum = BitConverter.GetBytes(packet.CheckSum); Byte[] b_id = BitConverter.GetBytes(packet.Identifier); Byte[] b_seq = BitConverter.GetBytes(packet.SequenceNumber); // Console.WriteLine("Serialize type "); Array.Copy(b_type, 0, Buffer, Index, b_type.Length); Index += b_type.Length; // Console.WriteLine("Serialize code "); Array.Copy(b_code, 0, Buffer, Index, b_code.Length); Index += b_code.Length; // Console.WriteLine("Serialize cksum "); Array.Copy(b_cksum, 0, Buffer, Index, b_cksum.Length); Index += b_cksum.Length; // Console.WriteLine("Serialize id "); Array.Copy(b_id, 0, Buffer, Index, b_id.Length); Index += b_id.Length; Array.Copy(b_seq, 0, Buffer, Index, b_seq.Length); Index += b_seq.Length; // copy the data Array.Copy(packet.Data, 0, Buffer, Index, PingData); Index += PingData; if (Index != PacketSize /* sizeof(IcmpPacket) */) { cbReturn = -1; return(cbReturn); } cbReturn = Index; return(cbReturn); }
private int CreatePacket(IcmpPacket packet, byte[] buffer, int packetSize, int pingData) { int result = 0; int destinationIndex = 0; byte[] sourceArray = new byte[] { packet.Type }; byte[] buffer3 = new byte[] { packet.SubCode }; byte[] bytes = BitConverter.GetBytes(packet.CheckSum); byte[] buffer5 = BitConverter.GetBytes(packet.Identifier); byte[] buffer6 = BitConverter.GetBytes(packet.SequenceNumber); Array.Copy(sourceArray, 0, buffer, destinationIndex, sourceArray.Length); destinationIndex += sourceArray.Length; Array.Copy(buffer3, 0, buffer, destinationIndex, buffer3.Length); destinationIndex += buffer3.Length; Array.Copy(bytes, 0, buffer, destinationIndex, bytes.Length); destinationIndex += bytes.Length; Array.Copy(buffer5, 0, buffer, destinationIndex, buffer5.Length); destinationIndex += buffer5.Length; Array.Copy(buffer6, 0, buffer, destinationIndex, buffer6.Length); destinationIndex += buffer6.Length; Array.Copy(packet.Data, 0, buffer, destinationIndex, pingData); destinationIndex += pingData; if (destinationIndex != packetSize) { result = SOCKET_ERROR; } else { result = destinationIndex; } sourceArray = null; buffer3 = null; bytes = null; buffer5 = null; buffer6 = null; return(result); }
/// <summary> /// Processes the queue of incoming IP packets. /// </summary> void ProcessPackets() { try { var tuple = inputQueue.Dequeue(); var packet = tuple.Item1; var ifc = tuple.Item2; packet.TimeToLive--; // Drop packet and send "TTL Expired"-ICMP back to packet originator. if (packet.TimeToLive == 0) { if (packet.Protocol != IpProtocol.Icmp) { SendIcmp(ifc, packet.Source, IcmpPacket.TimeExceeded(packet)); } return; } // Incrementally update the checksum. var sum = (uint)(packet.Checksum + 0x01); packet.Checksum = (ushort)(sum + (sum >> 16)); if (IsPacketForUs(packet)) { // See if we have all parts and can reassemble the original packet. if (IsFragment(packet)) { ReassemblePacket(packet); } else { // If it's not a fragment, hand the data up to the transport layer. HandUp(packet.Data, packet.Protocol); } } else { // If it's not for us, see if we can forward it to its destination. RoutePacket(packet, ifc); } } finally { // Nodal processing delay is the time it takes on average to process // a single IP packet. if (inputQueue.Count > 0) { Simulation.Callback(nodalProcessingDelay, ProcessPackets); } } }
private void SendPing(EndPoint ep) { DynamicArray <byte> packet; if (MeasureTime) { var cms = _pingStopwatch.ElapsedTicks; var bcms = BitConverter.GetBytes(cms); packet = new IcmpPacket(bcms).GeneratePayload(); } else { packet = _payloadData; } _socket.BeginSendTo(packet.Value, 0, packet.Size, SocketFlags.None, ep, null, null); }
public void HandleIcmpPacket(IPv4Datagram datagram) { IcmpPacket packet = datagram.HandleIcmpPacket(); ListViewItem item = new ListViewItem(count.ToString()); item.SubItems.Add(datagram.SourceName); item.SubItems.Add(datagram.DestinationName); item.SubItems.Add(consts.GetTypeForIcmp(packet.Type) + " {" + packet.Type.ToString() + "}"); item.SubItems.Add(consts.GetCodeForIcmp(packet.Type, packet.Code) + " {" + packet.Code.ToString() + "}"); item.SubItems.Add(packet.Checksum.ToString()); lstwICMP.Items.Add(item); packets.Add(GetHashString(), datagram); count++; lblCount.Text = count.ToString(); this.Update(); }
public void SendEcho() { var sendTime = BitConverter.GetBytes(HiResTimer.Now()); var body = new byte[_signature.Length + sendTime.Length]; Buffer.BlockCopy(_signature, 0, body, 0, _signature.Length); Buffer.BlockCopy(sendTime, 0, body, _signature.Length, sendTime.Length); var packet = new IcmpPacket { Data = body }; var bytes = packet.Format(); var sendArgs = new SocketAsyncEventArgs { RemoteEndPoint = _endPoint }; sendArgs.SetBuffer(bytes, 0, bytes.Length); // send echo _socket.SendToAsync(sendArgs); // if first, start listening for echo replies if (Interlocked.CompareExchange(ref _recv, 1, 0) == 0) StartRecv(); }
internal static Int32 Serialize(IcmpPacket packet, Byte [] Buffer, Int32 PacketSize, Int32 PingData) { Int32 cbReturn = 0; int Index = 0; Byte [] b_type = new Byte[1]; b_type[0] = (packet.Type); Byte [] b_code = new Byte[1]; b_code[0] = (packet.SubCode); Byte [] b_cksum = BitConverter.GetBytes(packet.CheckSum); Byte [] b_id = BitConverter.GetBytes(packet.Identifier); Byte [] b_seq = BitConverter.GetBytes(packet.SequenceNumber); Array.Copy(b_type, 0, Buffer, Index, b_type.Length); Index += b_type.Length; Array.Copy(b_code, 0, Buffer, Index, b_code.Length); Index += b_code.Length; Array.Copy(b_cksum, 0, Buffer, Index, b_cksum.Length); Index += b_cksum.Length; Array.Copy(b_id, 0, Buffer, Index, b_id.Length); Index += b_id.Length; Array.Copy(b_seq, 0, Buffer, Index, b_seq.Length); Index += b_seq.Length; Array.Copy(packet.Data, 0, Buffer, Index, PingData); Index += PingData; if (Index != PacketSize /* sizeof(IcmpPacket) */) { cbReturn = -1; return(cbReturn); } cbReturn = Index; return(cbReturn); }
///<summary>This sends an Icmp Request to the specified address, we want ///him to respond to us, so we can guarantee that by pretending to be the ///Server (i.e. x.y.z.1). We'll get a response in our main thread.</summary> ///<param name="dest_ip">Destination IP of our request.</summary> protected virtual void SendIcmpRequest(MemBlock dest_ip) { if (_dhcp_server == null) { return; } MemBlock ether_addr = null; if (!_ip_to_ether.TryGetValue(dest_ip, out ether_addr)) { ether_addr = EthernetPacket.BroadcastAddress; } IcmpPacket icmp = new IcmpPacket(IcmpPacket.Types.EchoRequest); IPPacket ip = new IPPacket(IPPacket.Protocols.Icmp, _dhcp_server.ServerIP, dest_ip, icmp.Packet); EthernetPacket ether = new EthernetPacket(ether_addr, EthernetPacket.UnicastAddress, EthernetPacket.Types.IP, ip.ICPacket); Ethernet.Send(ether.ICPacket); }
private void _read() { switch (Protocol) { case ProtocolEnum.Ipv6Nonxt: { _body = new NoNextHeader(m_io, this, m_root); break; } case ProtocolEnum.Ipv4: { _body = new Ipv4Packet(m_io); break; } case ProtocolEnum.Udp: { _body = new UdpDatagram(m_io); break; } case ProtocolEnum.Icmp: { _body = new IcmpPacket(m_io); break; } case ProtocolEnum.Hopopt: { _body = new OptionHopByHop(m_io, this, m_root); break; } case ProtocolEnum.Ipv6: { _body = new Ipv6Packet(m_io); break; } case ProtocolEnum.Tcp: { _body = new TcpSegment(m_io); break; } } }
/// <summary> /// Attempts to route the specified packet. /// </summary> /// <param name="packet">The packet to route.</param> /// <param name="ifc">The interface through which the packet was /// received.</param> void RoutePacket(IpPacket packet, Interface ifc) { // See if we can find a machting route in our routing table. var route = FindRoute(packet); // Drop packet and send "Unreachable" ICMP back to packet originator. if (route == null) { SendIcmp(ifc, packet.Source, IcmpPacket.Unreachable(packet)); return; } // Do we have to fragment the packet? if (route.Interface.MaximumTransmissionUnit < packet.TotalLength) { // Drop packet and send "Fragmentation Required" ICMP back to // packet originator. if (packet.Flags.HasFlag(IpFlag.DontFragment)) { SendIcmp(ifc, packet.Source, IcmpPacket.FragmentationRequired(packet)); return; } var packets = FragmentPacket(packet, route.Interface.MaximumTransmissionUnit); // Forward fragmented packets. foreach (var p in packets) { Output(route.Interface, route.Gateway != null ? route.Gateway : p.Destination, p); } } else { // Forward packet. Output(route.Interface, route.Gateway != null ? route.Gateway : packet.Destination, packet); } }
/// <summary> /// This method takes the "hostname" of the server /// and then it ping's it and shows the response time /// </summary> public static void PingHost(string host) { //Declare the IPHostEntry IPHostEntry serverHE, fromHE; int nBytes = 0; int dwStart = 0, dwStop = 0; //Initilize a Socket of the Type ICMP Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); // Get the server endpoint try { serverHE = Dns.GetHostByName(host); } catch(Exception) { Console.WriteLine("Host not found"); // fail return ; } // Convert the server IP_EndPoint to an EndPoint IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0], 0); EndPoint epServer = (ipepServer); // Set the receiving endpoint to the client machine fromHE = Dns.GetHostByName(Dns.GetHostName()); IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0], 0); EndPoint EndPointFrom = (ipEndPointFrom); int PacketSize = 0; IcmpPacket packet = new IcmpPacket(); // Construct the packet to send packet.Type = ICMP_ECHO; //8 packet.SubCode = 0; packet.CheckSum = UInt16.Parse("0"); packet.Identifier = UInt16.Parse("45"); packet.SequenceNumber = UInt16.Parse("0"); int PingData = 32; // sizeof(IcmpPacket) - 8; packet.Data = new Byte[PingData]; //Initilize the Packet.Data for (int i = 0; i < PingData; i++) { packet.Data[i] = (byte)'#'; } //Variable to hold the total Packet size PacketSize = PingData + 8; Byte [] icmp_pkt_buffer = new Byte[ PacketSize ]; Int32 Index = 0; //Call a Methos Serialize which counts //The total number of Bytes in the Packet Index = Serialize( packet, icmp_pkt_buffer, PacketSize, PingData ); //Error in Packet Size if( Index == -1 ) { Console.WriteLine("Error in Making Packet"); return ; } // now get this critter into a UInt16 array //Get the Half size of the Packet Double double_length = Convert.ToDouble(Index); Double dtemp = Math.Ceiling( double_length / 2); int cksum_buffer_length = Convert.ToInt32(dtemp); //Create a Byte Array UInt16 [] cksum_buffer = new UInt16[cksum_buffer_length]; //Code to initilize the Uint16 array int icmp_header_buffer_index = 0; for( int i = 0; i < cksum_buffer_length; i++ ) { cksum_buffer[i] = BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index); icmp_header_buffer_index += 2; } //Call a method which will return a checksum UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length); //Save the checksum to the Packet packet.CheckSum = u_cksum; // Now that we have the checksum, serialize the packet again Byte [] sendbuf = new Byte[ PacketSize ]; //again check the packet size Index = Serialize( packet, sendbuf, PacketSize, PingData ); //if there is a error report it if( Index == -1 ) { Console.WriteLine("Error in Making Packet"); return ; } dwStart = System.Environment.TickCount; // Start timing //send the Pack over the socket if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR) { Console.WriteLine("Socket Error cannot Send Packet"); } // Initialize the buffers. The receive buffer is the size of the // ICMP header plus the IP header (20 bytes) Byte [] ReceiveBuffer = new Byte[256]; nBytes = 0; //Receive the bytes bool recd =false ; int timeout=0 ; //loop for checking the time of the server responding while(!recd) { nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom); if (nBytes == SOCKET_ERROR) { Console.WriteLine("Host not Responding") ; recd=true ; break; } else if(nBytes>0) { dwStop = System.Environment.TickCount - dwStart; // stop timing Console.WriteLine("Reply from "+epServer.ToString()+" in "+dwStop+"MS :Bytes Received"+nBytes); recd=true; break; } timeout=System.Environment.TickCount - dwStart; if(timeout>1000) { Console.WriteLine("Time Out") ; recd=true; } } //close the socket socket.Close(); }
public static ICMPErrors PingHost(string host, out int dwStop) { System.Net.IPHostEntry serverHE, fromHE; int nBytes = 0; int dwStart = 0; dwStop = 0; try { System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Raw, System.Net.Sockets.ProtocolType.Icmp); try { serverHE = System.Net.Dns.GetHostByName(host); } catch (Exception) { return(ICMPErrors.ERROR_INVALID_HOST); } System.Net.IPEndPoint ipepServer = new System.Net.IPEndPoint(serverHE.AddressList[0], 0); System.Net.EndPoint epServer = (ipepServer); fromHE = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()); System.Net.IPEndPoint ipEndPointFrom = new System.Net.IPEndPoint(fromHE.AddressList[0], 0); System.Net.EndPoint EndPointFrom = (ipEndPointFrom); int PacketSize = 0; IcmpPacket packet = new IcmpPacket(); packet.Type = ICMP_ECHO; packet.SubCode = 0; packet.CheckSum = UInt16.Parse("0"); packet.Identifier = UInt16.Parse("45"); packet.SequenceNumber = UInt16.Parse("0"); int PingData = 32; packet.Data = new Byte[PingData]; for (int i = 0; i < PingData; i++) { packet.Data[i] = (byte)'#'; } PacketSize = PingData + 8; Byte [] icmp_pkt_buffer = new Byte[PacketSize]; Int32 Index = 0; Index = Serialize(packet, icmp_pkt_buffer, PacketSize, PingData); if (Index == -1) { return(ICMPErrors.ERROR_CONSTRUCTING_PACKET); } Double double_length = Convert.ToDouble(Index); Double dtemp = System.Math.Ceiling(double_length / 2); int cksum_buffer_length = Convert.ToInt32(dtemp); UInt16 [] cksum_buffer = new UInt16[cksum_buffer_length]; int icmp_header_buffer_index = 0; for (int i = 0; i < cksum_buffer_length; i++) { cksum_buffer[i] = BitConverter.ToUInt16(icmp_pkt_buffer, icmp_header_buffer_index); icmp_header_buffer_index += 2; } UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length); packet.CheckSum = u_cksum; Byte [] sendbuf = new Byte[PacketSize]; Index = Serialize(packet, sendbuf, PacketSize, PingData); if (Index == -1) { return(ICMPErrors.ERROR_CONSTRUCTING_PACKET); } dwStart = System.Environment.TickCount; if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR) { return(ICMPErrors.ERROR_CANNOT_SEND_PACKET); } System.Collections.ArrayList arrSocket = new System.Collections.ArrayList(); for (int i = 0; i < 5; i++) { arrSocket.Add(socket); System.Net.Sockets.Socket.Select(arrSocket, null, null, 1000000); if (socket.Available > 0) { dwStop = System.Environment.TickCount - dwStart; socket.Close(); return(ICMPErrors.ERROR_NONE); } } } catch (System.Exception) { dwStop = -1; return(ICMPErrors.ERROR_UNKNOW); } dwStop = -1; return(ICMPErrors.ERROR_HOST_TIMEOUT); }
public static bool PingHost(string host) { //Declare the IPHostEntry System.Net.IPHostEntry serverHE, fromHE; int nBytes = 0; int dwStart = 0, dwStop = 0; //Initilize a Socket of the Type ICMP System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Raw, System.Net.Sockets.ProtocolType.Icmp); // Get the server endpoint try { //serverHE = System.Net.Dns.GetHostByName(host); serverHE = System.Net.Dns.GetHostEntry(host); } catch (Exception) { errorstring = "未找到主机"; //Console.WriteLine("Host not found"); // fail return(false); } // Convert the server IP_EndPoint to an // EndPoint System.Net.IPAddress ipbind = null; System.Net.IPEndPoint ipepServer = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(host), 0); System.Net.EndPoint epServer = (ipepServer); // Set the receiving endpoint to the cli // ent machine //fromHE = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()); fromHE = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); foreach (System.Net.IPAddress ip in fromHE.AddressList) { if (System.Net.Sockets.AddressFamily.InterNetwork.Equals(ip.AddressFamily)) { ipbind = ip; break; } } System.Net.IPEndPoint ipEndPointFrom = new System.Net.IPEndPoint(ipbind, 0); System.Net.EndPoint EndPointFrom = (ipEndPointFrom); int PacketSize = 0; IcmpPacket packet = new IcmpPacket(); // Construct the packet to send packet.Type = ICMP_ECHO; //8 packet.SubCode = 0; packet.CheckSum = UInt16.Parse("0"); packet.Identifier = UInt16.Parse("45"); packet.SequenceNumber = UInt16.Parse("0"); int PingData = 32; // sizeof(IcmpPacket) - 8; packet.Data = new Byte[PingData]; //Initilize the Packet.Data for (int i = 0; i < PingData; i++) { packet.Data[i] = (byte)'#'; } //Variable to hold the total Packet size // PacketSize = PingData + 8; Byte[] icmp_pkt_buffer = new Byte[PacketSize]; Int32 Index = 0; //Call a Methos Serialize which counts //The total number of Bytes in the Packe // t Index = Serialize( packet, icmp_pkt_buffer, PacketSize, PingData); //Error in Packet Size if (Index == -1) { Console.WriteLine("Error in Making Packet"); errorstring = "创建封包错误"; return(false); } // now get this critter into a UInt16 ar // ray //Get the Half size of the Packet Double double_length = Convert.ToDouble(Index); Double dtemp = System.Math.Ceiling(double_length / 2); int cksum_buffer_length = Convert.ToInt32(dtemp); //Create a Byte Array UInt16[] cksum_buffer = new UInt16[cksum_buffer_length]; //Code to initilize the Uint16 array int icmp_header_buffer_index = 0; for (int i = 0; i < cksum_buffer_length; i++) { cksum_buffer[i] = BitConverter.ToUInt16(icmp_pkt_buffer, icmp_header_buffer_index); icmp_header_buffer_index += 2; } //Call a method which will return a chec // ksum UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length); //Save the checksum to the Packet packet.CheckSum = u_cksum; // Now that we have the checksum, serial // ize the packet again Byte[] sendbuf = new Byte[PacketSize]; //again check the packet size Index = Serialize( packet, sendbuf, PacketSize, PingData); //if there is a error report it if (Index == -1) { Console.WriteLine("Error in Making Packet"); errorstring = "添加校验码后的封包错误"; return(false); } dwStart = System.Environment.TickCount; // Start timing Console.WriteLine(dwStart.ToString()); //send the Pack over the socket if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR) { Console.WriteLine("Socket Error cannot Send Packet"); errorstring = "SendTo方法失败"; return(false); } // Initialize the buffers. The receive b // uffer is the size of the // ICMP header plus the IP header (20 by // tes) Byte[] ReceiveBuffer = new Byte[256]; nBytes = 0; //Receive the bytes bool recd = false; int timeout = 0; //loop for checking the time of the serv // er responding while (!recd) { socket.ReceiveTimeout = pingtimeout; try { nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom); Console.WriteLine(nBytes.ToString()); if (nBytes == SOCKET_ERROR) { //Console.WriteLine("Host not Responding"); errorstring = "主机没有响应"; recd = true; return(false); } else if (nBytes > 0) { dwStop = System.Environment.TickCount - dwStart; // stop timing Console.WriteLine("Reply from " + epServer.ToString() + " in " + dwStop + "ms => Bytes Received: " + nBytes); recd = true; return(true); } timeout = System.Environment.TickCount - dwStart; Console.WriteLine(timeout.ToString()); //if (timeout > 1000) //{ // Console.WriteLine("Time Out"); // recd = true; // return false; //} } catch (Exception ex) { if (Global.IsShowBug) { System.Windows.Forms.MessageBox.Show(ex.Message); } errorstring = ex.Message; return(false); } } //close the socket socket.Close(); return(false); }
static void UsrTrasert(string HostName) { Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 2000); IPHostEntry HostData = null; IPEndPoint IPendPoint = null; EndPoint endPoint = null; try { // Получение списка IP-адресов, за которыми закреплен домен. HostData = Dns.GetHostEntry(HostName); IPendPoint = new IPEndPoint(HostData.AddressList[0], 25000); endPoint = new IPEndPoint(HostData.AddressList[0], 25000); string endPointString = endPoint.ToString(); endPointString = endPointString.Substring(0, endPointString.Length - 6); Console.WriteLine("Starting to send packets to " + endPointString); Console.WriteLine(); } catch { Console.WriteLine(); Console.WriteLine("Wrong domain or another issue occured"); Environment.Exit(0); } IcmpPacket icmpPacket = new IcmpPacket(); // Длина блока данных = 2 (ID) + 2 (SeqNum) + Length(MessageData) icmpPacket.DataLength = 4 + icmpPacket.MsgData.Length; // Длина пакета = 1 (Type) + 1 (Code) + 2 (Checksum) + DataLength int PkgSize = 4 + icmpPacket.DataLength; icmpPacket.Checksum = icmpPacket.GetChecksum(); for (int ttl = 1; ttl <= maxTTL; ttl++) { host.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, ttl); int badAttempt = 0; int PkgLength = 0; try { DateTime timestart; TimeSpan[] MsgArrivalTime = new TimeSpan[3]; byte[] data = null; for (int i = 0; i <= 2; i++) { timestart = DateTime.Now; host.SendTo(icmpPacket.ToBytes(), PkgSize, SocketFlags.None, IPendPoint); data = new byte[1024]; PkgLength = host.ReceiveFrom(data, ref endPoint); MsgArrivalTime[i] = DateTime.Now - timestart; } string endPointString = endPoint.ToString(); endPointString = endPointString.Substring(0, endPointString.Length - 2); // Проверка типа полученного пакета. // 11 - ttl expired. if (data[20] == 11) { Console.WriteLine(ttl + " " + (MsgArrivalTime[0].Milliseconds.ToString()) + " мс " + (MsgArrivalTime[1].Milliseconds.ToString()) + " мс " + (MsgArrivalTime[2].Milliseconds.ToString()) + " мс: " + endPointString); Console.WriteLine(); } // 0 - echo-answer. if (data[20] == 0) { Console.WriteLine(ttl + " " + (MsgArrivalTime[0].Milliseconds.ToString()) + " мс " + (MsgArrivalTime[1].Milliseconds.ToString()) + " мс " + (MsgArrivalTime[2].Milliseconds.ToString()) + " мс: " + endPointString + ": the target is reached"); break; } } catch (SocketException) { Console.WriteLine(ttl + " no answer from " + endPoint); Console.WriteLine(); badAttempt++; if (badAttempt == 3) { Console.WriteLine("Impossible to reach the host"); } } } host.Close(); }
public RawPing() { _pingStopwatch = Stopwatch.StartNew(); _payloadData = IcmpPacket.GenerateNew(); }
public override void Try() { int nBytes; int dwStart, dwStop; IPEndPoint remoteIPEndPoint; EndPoint lep, rep; StringBuilder sb = new StringBuilder(); try { //ローカル側のエンドポイントを設定 if (localIpAddress == string.Empty) { localIPEndPoint = new IPEndPoint(0, 0); } else { localIPEndPoint = new IPEndPoint(IPAddress.Parse(localIpAddress), 0); } //リモート側のエンドポイントを設定 remoteIPEndPoint = new IPEndPoint(IPAddress.Parse(remoteIpAddress), 0); rep = (EndPoint)remoteIPEndPoint; //ソケットの初期化 ICMPで socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); //送信元ソケットをバインド socket.Bind(localIPEndPoint); lep = (EndPoint)localIPEndPoint; } catch (Exception ex) { failure(); sb.Append("ping-ng-to ").Append(remoteIpAddress).Append(" ").Append(ex.Message); outputMessage(sb.ToString()); return; } int PacketSize = 0; IcmpPacket packet = new IcmpPacket(); // Construct the packet to send packet.Type = ICMP_ECHO; //8 packet.SubCode = 0; packet.CheckSum = UInt16.Parse("0"); packet.Identifier = UInt16.Parse("45"); packet.SequenceNumber = UInt16.Parse("0"); int PingData = 32; // sizeof(IcmpPacket) - 8; packet.Data = new Byte[PingData]; //Initilize the Packet.Data for (int i = 0; i < PingData; i++) { packet.Data[i] = (byte)'A'; } //Variable to hold the total Packet size PacketSize = PingData + 8; Byte[] icmp_pkt_buffer = new Byte[PacketSize]; Int32 Index = 0; //Call a Method Serialize which counts //The total number of Bytes in the Packet Index = Serialize(packet, icmp_pkt_buffer, PacketSize, PingData); //Error in Packet Size if (Index == -1) { failure(); sb.Append("ping-ng-to ").Append(remoteIpAddress).Append(" ").Append("Error in Making Packet (base)"); outputMessage(sb.ToString()); return; } // now get this critter into a UInt16 array //Get the Half size of the Packet Double double_length = Convert.ToDouble(Index); Double dtemp = Math.Ceiling(double_length / 2); int cksum_buffer_length = Convert.ToInt32(dtemp); //Create a Byte Array UInt16[] cksum_buffer = new UInt16[cksum_buffer_length]; //Code to initialize the Uint16 array int icmp_header_buffer_index = 0; for (int i = 0; i < cksum_buffer_length; i++) { cksum_buffer[i] = BitConverter.ToUInt16(icmp_pkt_buffer, icmp_header_buffer_index); icmp_header_buffer_index += 2; } //Call a method which will return a checksum UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length); //Save the checksum to the Packet packet.CheckSum = u_cksum; // Now that we have the checksum, serialize the packet again Byte[] sendbuf = new Byte[PacketSize]; //again check the packet size Index = Serialize(packet, sendbuf, PacketSize, PingData); //if there is a error report it if (Index == -1) { failure(); sb.Append("ping-ng-to ").Append(remoteIpAddress).Append(" ").Append("Error in Making Packet (checksum)"); outputMessage(sb.ToString()); return; } //送信 dwStart = System.Environment.TickCount; // Start timing socket.SendTimeout = timeout; /* if ((nBytes = socket.SendTo(sendbuf, PacketSize, SocketFlags.None, rep)) == SOCKET_ERROR) { * failure(); * outputMessage("ping-ng-to " + remoteIpAddress + " " + "Socket Error cannot Send Packet"); * } */ try { nBytes = socket.SendTo(sendbuf, PacketSize, SocketFlags.None, rep); } catch (Exception ex) { failure(); sb.Append("ping-ng-to ").Append(remoteIpAddress).Append(" ").Append(ex.Message); outputMessage(sb.ToString()); return; } localIPEndPoint = (IPEndPoint)socket.LocalEndPoint; //受信 Byte[] ReceiveBuffer = new Byte[1024]; nBytes = 0; socket.ReceiveTimeout = timeout; try { nBytes = socket.ReceiveFrom(ReceiveBuffer, ref rep); } catch (Exception ex) { failure(); sb.Append("ping-ng-to ").Append(remoteIpAddress).Append(" ").Append(ex.Message); outputMessage(sb.ToString()); return; } dwStop = System.Environment.TickCount - dwStart; // stop timing success(); sb.Append("ping-ok-to "); sb.Append(remoteIpAddress); sb.Append(":"); sb.Append(portNo); sb.Append("/"); sb.Append(protocolName.ToString()); sb.Append(" "); sb.Append(dwStop); sb.Append("ms"); outputMessage(sb.ToString()); socket.Close(); }
public int Ping(string host, int timeout) { double startTime = 0; int pingTime = -1; int pingDataSize = 4; // Ping packet payload, dummy data int packetSize = pingDataSize + 8; // Ping payload + ICMP header // Convert IP address string to something we can use IPEndPoint ipepServer; try { ipepServer = new IPEndPoint(IPAddress.Parse(host),0); } catch (Exception e) { Debug.Log("Error parsing IP address: " + e.ToString()); return -1; } EndPoint epServer = (ipepServer); Socket socket = new Socket(ipepServer.AddressFamily, SocketType.Dgram, ProtocolType.Icmp); socket.ReceiveTimeout = timeout; // Create packet IcmpPacket packet = new IcmpPacket(); packet.type = 8; // ICMP echo request packet.subCode = 0; packet.checkSum = 0; packet.identifier = 1; packet.sequenceNumber = 0; packet.data = new Byte[pingDataSize]; for (int i = 0; i < pingDataSize; i++) { packet.data[i] = (byte)'.'; } Byte [] icmpPacket = new Byte[packetSize]; // Populate buffer Serialize(packet, icmpPacket, pingDataSize); // Generate checksum UInt16 [] checksum = new UInt16[(int)((float)packetSize/2)]; //Debug.Log("Checksum length is " + checksum.Length); int icmpPacketIndex = 0; for( int i = 0; i < checksum.Length; i++ ) { checksum[i] = BitConverter.ToUInt16(icmpPacket,icmpPacketIndex); icmpPacketIndex += 2; } packet.checkSum = generateChecksum(checksum, checksum.Length); // Repopulate packet with generated checksum Byte [] sendBuffer = new Byte[packetSize]; Serialize(packet, sendBuffer, pingDataSize); // Send the ping packet startTime = Network.time; if (socket.SendTo(sendBuffer, packetSize, 0, epServer) == 0) { Debug.Log("Socket Error cannot Send Packet"); } // Receive ping response Byte [] rcvBuffer = new Byte[256]; try { //socket.ReceiveFrom(rcvBuffer, ref epServer); socket.Receive(rcvBuffer); double stopTime = Network.time; pingTime = (int)((stopTime - startTime)*1000); //Debug.Log("Reply from "+epServer.ToString()+" containing "+rcvBytes+" bytes in "+pingTime+" ms"); } catch (SocketException e) { Debug.Log("Socket error: " + e.ToString()); } catch (Exception e) { Debug.Log("Exception occured when receiving " + e.ToString()); } socket.Close(); return pingTime; }
private Byte Type; // type of message #endregion Fields #region Methods public static IcmpPacket CreatePacket( ) { IcmpPacket packet = new IcmpPacket(); packet.Type = ICMP_ECHO; //8 packet.SubCode = 0; packet.CheckSum = 0xcd98; // no need to compute it packet.Identifier = UInt16.Parse( "45" ); packet.SequenceNumber = UInt16.Parse( "0" ); int PingData = 32; packet.Data = new Byte[PingData]; //Initilize the Packet.Data for(int i = 0; i < PingData; i++) { packet.Data[ i ] = (byte) '#'; } return packet; }
public void packetTvwDecode(byte [] capPacket, TreeView tvwDecode) { #region Parse Ethernet Header Ethernet802_3 ethernet = new Ethernet802_3(capPacket); strSourceMacAddress = ethernet.SourceMACAddress.ToString(); strDestMacAddress = ethernet.DestinationMACAddress.ToString(); strEthernet = "Ethernet II, Src: " + strSourceMacAddress + ", Dst: " + strDestMacAddress; strSrcMac = "Source: " + strSourceMacAddress; strDstMac = "Destination: " + strDestMacAddress; strEthernetType = "Type: " + ethernet.NetworkProtocol.ToString(); strData = "Data: " + ethernet.Data.ToString(); TreeNode nodeEthernet = tvwDecode.Nodes.Add(strEthernet); TreeNode nodeEthernetDstMac = nodeEthernet.Nodes.Add(strDstMac); TreeNode nodeEthernetSrcMac = nodeEthernet.Nodes.Add(strSrcMac); TreeNode nodeType = nodeEthernet.Nodes.Add(strEthernetType); TreeNode nodeData = nodeEthernet.Nodes.Add(strData); #region Parse Network Protocol switch (ethernet.NetworkProtocol) { case NetworkLayerProtocol.IP: IpV4Packet ip = new IpV4Packet(ethernet.Data); strIp = "Internet Protocol, Src Addr: " + ip.SourceAddress.ToString() + ", Dest Addr: " + ip.DestinationAddress.ToString(); strIpVersion = "Version: " + ip.Version.ToString(); int intIpHeaderLengthHex = ip.HeaderLength; int intIpHeaderLengthBytes = intIpHeaderLengthHex * 4; strIpHeaderLength = "Header Length: " + intIpHeaderLengthBytes.ToString() + " bytes"; strTypeOfService = "Type of Service: " + ip.TypeOfService.ToString(); strIpTotalLength = "Total Length: " + ip.TotalLength.ToString(); strIpIdentification = "Identification: " + ip.Identification.ToString(); strIpFlags = "Flags: " + ip.ControlFlags.ToString(); strIpFragment = "Fragment Offset: " + ip.Fragments.ToString(); strIpTtl = "Time To Live: " + ip.TimeToLive.ToString(); strIpProtocol = "Protocol: " + ip.TransportProtocol.ToString(); strIpChecksum = "Header Checksum: " + ip.Checksum.ToString(); if (ip.Options != null) { strIpOptions = "Options: " + ip.Options.ToString(); } if (ip.Padding != null) { strIpPadding = "Padding: " + ip.Padding.ToString(); } TreeNode nodeIP = tvwDecode.Nodes.Add(strIp); TreeNode nodeIpVersion = nodeIP.Nodes.Add(strIpVersion); TreeNode nodeIpHeaderLength = nodeIP.Nodes.Add(strIpHeaderLength); TreeNode nodeTypeOfService = nodeIP.Nodes.Add(strTypeOfService); TreeNode nodeIpTotalLength = nodeIP.Nodes.Add(strIpTotalLength); TreeNode nodeIpIdentification = nodeIP.Nodes.Add(strIpIdentification); TreeNode nodeIpFlags = nodeIP.Nodes.Add(strIpFlags); TreeNode nodeIpFragment = nodeIP.Nodes.Add(strIpFragment); TreeNode nodeIpTtl = nodeIP.Nodes.Add(strIpTtl); TreeNode nodeIpProtocol = nodeIP.Nodes.Add(strIpProtocol); TreeNode nodeIpChecksum = nodeIP.Nodes.Add(strIpChecksum); TreeNode nodeIpOptions = null; TreeNode nodeIpPadding = null; if (ip.Options != null) { nodeIpOptions = nodeIP.Nodes.Add(strIpOptions); } if (ip.Padding != null) { nodeIpPadding = nodeIP.Nodes.Add(strIpPadding); } //TreeNode nodeData = tvwDecode.Nodes.Add(strData); #region Parse Transport Protocol switch (ip.TransportProtocol) { case ProtocolType.Tcp: TcpPacket tcp = new TcpPacket(ip.Data); strTcp = "Transmission Control Protocol, Src Port: " + tcp.SourcePort.ToString() + ", Dst Port: " + tcp.DestinationPort.ToString() + ", Seq: " + tcp.SequenceNumber.ToString() + ", Ack: " + tcp.AcknowledgmentNumber.ToString(); strTcpSrcPort = "Source port: " + tcp.SourcePort.ToString(); strTcpDstPort = "Destination port: " + tcp.DestinationPort.ToString(); strTcpSeq = "Sequence number: " + tcp.SequenceNumber.ToString(); strTcpAck = "Acknowledgement number: " + tcp.AcknowledgmentNumber.ToString(); strTcpOffset = "Offset: " + tcp.Offset.ToString(); strTcpFlags = "Flags: " + tcp.Flags.ToString(); strTcpWindow = "Window size: " + tcp.Window.ToString(); strTcpChecksum = "Checksum: " + tcp.Checksum.ToString(); strTcpUrgetPointer = "Urgent Pointer: " + tcp.UrgentPointer.ToString(); if (tcp.Options != null) { strTcpOptions = "Options: " + tcp.Options.ToString(); } if (tcp.Padding != null) { strTcpPadding = "Padding: " + tcp.Padding.ToString(); } if (tcp.Data != null) { strTcpData = "Data: " + tcp.Data.ToString(); } TreeNode nodeTcp = tvwDecode.Nodes.Add(strTcp); TreeNode nodeTcpSrcPort = nodeTcp.Nodes.Add(strTcpSrcPort); TreeNode nodeTcpDstPort = nodeTcp.Nodes.Add(strTcpDstPort); TreeNode nodeTcpSeq = nodeTcp.Nodes.Add(strTcpSeq); TreeNode nodeTcpAck = nodeTcp.Nodes.Add(strTcpAck); TreeNode nodeTcpOffset = nodeTcp.Nodes.Add(strTcpOffset); TreeNode nodeTcpFlags = nodeTcp.Nodes.Add(strTcpFlags); TreeNode nodeTcpWindow = nodeTcp.Nodes.Add(strTcpWindow); TreeNode nodeTcpChecksum = nodeTcp.Nodes.Add(strTcpChecksum); TreeNode nodeTcpUrgetPointer = nodeTcp.Nodes.Add(strTcpUrgetPointer); TreeNode nodeTcpOptions = null; TreeNode nodeTcpPadding = null; TreeNode nodeTcpData = null; if (tcp.Options != null) { nodeTcpOptions = nodeTcp.Nodes.Add(strTcpOptions); } if (tcp.Padding != null) { nodeTcpPadding = nodeTcp.Nodes.Add(strTcpPadding); } if (tcp.Data != null) { nodeTcpData = nodeTcp.Nodes.Add(strTcpData); } break; case ProtocolType.Udp: UdpPacket udp = new UdpPacket(ip.Data); strUdp = "User Datagram Protocol, Src Port: " + udp.SourcePort.ToString() + ", Dst Port: " + udp.DestinationPort.ToString(); strUdpSrcPort = "Source port: " + udp.SourcePort.ToString(); strUdpDstPort = "Destination port: " + udp.DestinationPort.ToString(); strUdpLength = "Length: " + udp.Length.ToString(); strUdpChecksum = "Checksum: " + udp.Checksum.ToString(); if (udp.Data != null) { strUdpData = "Data: " + udp.Data.ToString(); } TreeNode nodeUdp = tvwDecode.Nodes.Add(strUdp); TreeNode nodeUdpSrcPort = nodeUdp.Nodes.Add(strUdpSrcPort); TreeNode nodeUdpDstPort = nodeUdp.Nodes.Add(strUdpDstPort); TreeNode nodeUdpLength = nodeUdp.Nodes.Add(strUdpLength); TreeNode nodeUdpChecksum = nodeUdp.Nodes.Add(strUdpChecksum); TreeNode nodeUdpData = null; if (udp.Data != null) { nodeUdpData = nodeUdp.Nodes.Add(strUdpData); } break; case ProtocolType.Icmp: IcmpPacket icmp = new IcmpPacket(ip.Data); strIcmp = "Internet Control Message Protocol"; strIcmpMessageType = "Data: " + icmp.MessageType.ToString(); strIcmpCode = "Data: " + icmp.Code.ToString(); strIcmpChecksum = "Data: " + icmp.Checksum.ToString(); strIcmpData = "Data: " + icmp.Data.ToString(); TreeNode nodeIcmp = tvwDecode.Nodes.Add(strIcmp); TreeNode nodeIcmpMessageType = nodeIcmp.Nodes.Add(strIcmpMessageType); TreeNode nodeIcmpCode = nodeIcmp.Nodes.Add(strIcmpCode); TreeNode nodeIcmpChecksum = nodeIcmp.Nodes.Add(strIcmpChecksum); TreeNode nodenodeIcmpData = nodeIcmp.Nodes.Add(strIcmpData); break; } #endregion break; case NetworkLayerProtocol.ARP: ArpPacket arp = new ArpPacket(ethernet.Data); strArp = "Address Resolution Protocol"; strArpMediaType = "Hardware Type: " + arp.MediaType.ToString(); strArpProtocolType = "Protocol Type: " + arp.Protocol.ToString(); strArpType = "Opcode: " + arp.Type.ToString(); strArpSrcMac = "Sender MAC Address: " + arp.SourceMACAddress.ToString(); strArpSrcIp = "Sender IP Address: " + arp.SourceIPAddress.ToString(); strArpDstMac = "Target MAC Address: " + arp.DestinationMACAddress.ToString(); strArpDstIp = "Target IP Address: " + arp.DestinationIPAddress.ToString(); TreeNode nodeArp = tvwDecode.Nodes.Add(strArp); TreeNode nodeMediaType = nodeArp.Nodes.Add(strArpMediaType); TreeNode nodeArpProtocolType = nodeArp.Nodes.Add(strArpProtocolType); TreeNode nodeArpType = nodeArp.Nodes.Add(strArpType); TreeNode nodeArpSrcMac = nodeArp.Nodes.Add(strArpSrcMac); TreeNode nodeArpSrcIp = nodeArp.Nodes.Add(strArpSrcIp); TreeNode nodeArpDstMac = nodeArp.Nodes.Add(strArpDstMac); TreeNode nodeArpDstIp = nodeArp.Nodes.Add(strArpDstIp); break; } #endregion #endregion }
private void btnStop_Click(object sender, EventArgs e) { if (driver.Disposed == true) { return; } captureThread.Abort(); driver.CloseDevice(); for (int packetLoop = 0; packetLoop < packetCount; packetLoop++) { string sourceIp = "N/A"; string sourceMac = "N/A"; string sourcePort = "N/A"; string destIp = "N/A"; string destMac = "N/A"; string destPort = "N/A"; string protocol = "N/A"; Ethernet802_3 ethernet = new Ethernet802_3(capturedPackets[packetLoop]); sourceMac = ethernet.SourceMACAddress.ToString(); destMac = ethernet.DestinationMACAddress.ToString(); switch (ethernet.NetworkProtocol) { case NetworkLayerProtocol.IP: IpV4Packet ip = new IpV4Packet(ethernet.Data); sourceIp = ip.SourceAddress.ToString(); destIp = ip.DestinationAddress.ToString(); protocol = ip.TransportProtocol.ToString().ToUpper(); switch (ip.TransportProtocol) { case ProtocolType.Tcp: TcpPacket tcp = new TcpPacket(ip.Data); sourcePort = tcp.SourcePort.ToString(); destPort = tcp.DestinationPort.ToString(); break; case ProtocolType.Udp: UdpPacket udp = new UdpPacket(ip.Data); sourcePort = udp.SourcePort.ToString(); destPort = udp.DestinationPort.ToString(); break; case ProtocolType.Icmp: IcmpPacket icmp = new IcmpPacket(ip.Data); break; } break; case NetworkLayerProtocol.ARP: ArpPacket arp = new ArpPacket(ethernet.Data); sourceMac = arp.SourceMACAddress.ToString(); destMac = arp.DestinationMACAddress.ToString(); sourceIp = arp.SourceIPAddress.ToString(); destIp = arp.DestinationIPAddress.ToString(); protocol = arp.Protocol.ToString().ToUpper(); break; } string[] items = new string[8]; items[0] = packetLoop.ToString(); items[1] = sourceIp; items[2] = sourceMac; items[3] = sourcePort; items[4] = destIp; items[5] = destMac; items[6] = destPort; items[7] = protocol; lvwPacketCapture.Items.Add(new ListViewItem(items, 0)); } }
public IcmpPacket(KaitaiStream p__io, KaitaiStruct p__parent = null, IcmpPacket p__root = null) : base(p__io) { m_parent = p__parent; m_root = p__root ?? this; _read(); }
public void addPacket(IPv4Datagram datagram, ref TreeView trv) { int [] xx = new int[4]; int total = datagram.Length + datagram.IHL; trv.Nodes.Clear(); TreeNode tn = new TreeNode("Packet (Size : " + total.ToString() + " )"); xx[0] = 0; xx[1] = total * 8 - 1; tn.Tag = xx; tn.ImageIndex = 2; tn.Nodes.Add("IP"); xx = new int[4]; xx[0] = 0; xx[1] = datagram.IHL * 8 - 1; tn.Nodes[0].Tag = xx; tn.Nodes[0].ImageIndex = 1; tn.Nodes[0].Nodes.Add("Version : 4"); xx = new int[4]; xx[0] = 0; xx[1] = 3; tn.Nodes[0].Nodes[0].Tag = xx; tn.Nodes[0].Nodes[0].ImageIndex = 4; tn.Nodes[0].Nodes.Add("IHL : " + datagram.IHL); xx = new int[4]; xx[0] = 4; xx[1] = 7; tn.Nodes[0].Nodes[1].Tag = xx; tn.Nodes[0].Nodes[1].ImageIndex = 4; tn.Nodes[0].Nodes.Add("Service Type : " + consts.GetTOSForIP(datagram.TypeOfService)); xx = new int[4]; xx[0] = 8; xx[1] = 15; tn.Nodes[0].Nodes[2].Tag = xx; tn.Nodes[0].Nodes[2].ImageIndex = 4; tn.Nodes[0].Nodes.Add("Total Length : " + total.ToString()); xx = new int[4]; xx[0] = 16; xx[1] = 31; tn.Nodes[0].Nodes[3].Tag = xx; tn.Nodes[0].Nodes[3].ImageIndex = 4; tn.Nodes[0].Nodes.Add("Identification : " + datagram.Identification.ToString()); xx = new int[4]; xx[0] = 32; xx[1] = 47; tn.Nodes[0].Nodes[4].Tag = xx; tn.Nodes[0].Nodes[4].ImageIndex = 4; tn.Nodes[0].Nodes.Add("Ip Flags"); xx = new int[4]; xx[0] = 48; xx[1] = 50; tn.Nodes[0].Nodes[5].Tag = xx; tn.Nodes[0].Nodes[5].ImageIndex = 4; tn.Nodes[0].Nodes[5].Nodes.Add("Reserved Flag : " + datagram.ReservedFlag.ToString()); xx = new int[4]; xx[0] = 48; xx[1] = 48; tn.Nodes[0].Nodes[5].Nodes[0].Tag = xx; tn.Nodes[0].Nodes[5].Nodes[0].ImageIndex = 3; tn.Nodes[0].Nodes[5].Nodes.Add("Dont Fragment : " + datagram.DontFragmentFlag.ToString()); xx = new int[4]; xx[0] = 49; xx[1] = 49; tn.Nodes[0].Nodes[5].Nodes[1].Tag = xx; tn.Nodes[0].Nodes[5].Nodes[1].ImageIndex = 3; tn.Nodes[0].Nodes[5].Nodes.Add("More Flag : " + datagram.MoreFlag.ToString()); xx = new int[4]; xx[0] = 50; xx[1] = 50; tn.Nodes[0].Nodes[5].Nodes[2].Tag = xx; tn.Nodes[0].Nodes[5].Nodes[2].ImageIndex = 3; tn.Nodes[0].Nodes.Add("Fragment Offset : " + datagram.FragmentOffset.ToString()); xx = new int[4]; xx[0] = 51; xx[1] = 63; tn.Nodes[0].Nodes[6].Tag = xx; tn.Nodes[0].Nodes[6].ImageIndex = 4; tn.Nodes[0].Nodes.Add("TTL : " + datagram.TTL.ToString()); xx = new int[4]; xx[0] = 64; xx[1] = 71; tn.Nodes[0].Nodes[7].Tag = xx; tn.Nodes[0].Nodes[7].ImageIndex = 4; tn.Nodes[0].Nodes.Add("Upper Protcol : " + datagram.UpperProtocol); xx = new int[4]; xx[0] = 72; xx[1] = 79; tn.Nodes[0].Nodes[8].Tag = xx; tn.Nodes[0].Nodes[8].ImageIndex = 4; tn.Nodes[0].Nodes.Add("CheckSum : " + datagram.Checksum.ToString()); xx = new int[4]; xx[0] = 80; xx[1] = 95; tn.Nodes[0].Nodes[9].Tag = xx; tn.Nodes[0].Nodes[9].ImageIndex = 4; tn.Nodes[0].Nodes.Add("Source : " + datagram.SourceName); xx = new int[4]; xx[0] = 96; xx[1] = 127; tn.Nodes[0].Nodes[10].Tag = xx; tn.Nodes[0].Nodes[10].ImageIndex = 4; tn.Nodes[0].Nodes.Add("Destination : " + datagram.DestinationName); xx = new int[4]; xx[0] = 128; xx[1] = 159; tn.Nodes[0].Nodes[11].Tag = xx; tn.Nodes[0].Nodes[11].ImageIndex = 4; if (datagram.IHL == 24) { tn.Nodes[0].Nodes.Add("Options (+Padding): " + datagram.Options.ToString()); xx = new int[4]; xx[0] = 160; xx[1] = datagram.IHL * 8 - 1; tn.Nodes[0].Nodes[12].Tag = xx; tn.Nodes[0].Nodes[12].ImageIndex = 4; } if (datagram.UpperProtocol == "Tcp") { TcpPacket tcpPacket = datagram.HandleTcpPacket(); tn.Nodes.Add("Tcp"); xx = new int[4]; xx[0] = datagram.IHL * 8; xx[1] = total * 8 - 1; tn.Nodes[1].Tag = xx; tn.Nodes[1].ImageIndex = 1; tn.Nodes[1].Nodes.Add("Source Port : " + tcpPacket.SourcePort.ToString() + " " + consts.GetTcpPorts(tcpPacket.SourcePort)); xx = new int[4]; xx[0] = datagram.IHL * 8; xx[1] = datagram.IHL * 8 + 15; tn.Nodes[1].Nodes[0].Tag = xx; tn.Nodes[1].Nodes[0].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Destination Port : " + tcpPacket.DestinationPort.ToString() + " " + consts.GetTcpPorts(tcpPacket.DestinationPort)); xx = new int[4]; xx[0] = datagram.IHL * 8 + 16; xx[1] = datagram.IHL * 8 + 31; tn.Nodes[1].Nodes[1].Tag = xx; tn.Nodes[1].Nodes[1].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Sequence : " + tcpPacket.Sequence); xx = new int[4]; xx[0] = datagram.IHL * 8 + 32; xx[1] = datagram.IHL * 8 + 63; tn.Nodes[1].Nodes[2].Tag = xx; tn.Nodes[1].Nodes[2].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Acknowledgement : " + tcpPacket.Acknowledgement); xx = new int[4]; xx[0] = datagram.IHL * 8 + 64; xx[1] = datagram.IHL * 8 + 95; tn.Nodes[1].Nodes[3].Tag = xx; tn.Nodes[1].Nodes[3].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Header Length : " + tcpPacket.DataOffset); xx = new int[4]; xx[0] = datagram.IHL * 8 + 96; xx[1] = datagram.IHL * 8 + 99; tn.Nodes[1].Nodes[4].Tag = xx; tn.Nodes[1].Nodes[4].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Flags"); xx = new int[4]; xx[0] = datagram.IHL * 8 + 106; xx[1] = datagram.IHL * 8 + 111; tn.Nodes[1].Nodes[5].Tag = xx; tn.Nodes[1].Nodes[5].ImageIndex = 4; tn.Nodes[1].Nodes[5].Nodes.Add("x..... URG : " + ((tcpPacket.Urgent)? 1 : 0)); xx = new int[4]; xx[0] = datagram.IHL * 8 + 106; xx[1] = datagram.IHL * 8 + 106; tn.Nodes[1].Nodes[5].Nodes[0].Tag = xx; tn.Nodes[1].Nodes[5].Nodes[0].ImageIndex = 3; tn.Nodes[1].Nodes[5].Nodes.Add(".x.... AKC : " + ((tcpPacket.Ack)? 1 : 0)); xx = new int[4]; xx[0] = datagram.IHL * 8 + 107; xx[1] = datagram.IHL * 8 + 107; tn.Nodes[1].Nodes[5].Nodes[1].Tag = xx; tn.Nodes[1].Nodes[5].Nodes[1].ImageIndex = 3; tn.Nodes[1].Nodes[5].Nodes.Add("..x... EOL : " + ((tcpPacket.Push)? 1 : 0)); xx = new int[4]; xx[0] = datagram.IHL * 8 + 108; xx[1] = datagram.IHL * 8 + 108; tn.Nodes[1].Nodes[5].Nodes[2].Tag = xx; tn.Nodes[1].Nodes[5].Nodes[2].ImageIndex = 3; tn.Nodes[1].Nodes[5].Nodes.Add("...x.. RST : " + ((tcpPacket.Reset)? 1 : 0)); xx = new int[4]; xx[0] = datagram.IHL * 8 + 109; xx[1] = datagram.IHL * 8 + 109; tn.Nodes[1].Nodes[5].Nodes[3].Tag = xx; tn.Nodes[1].Nodes[5].Nodes[3].ImageIndex = 3; tn.Nodes[1].Nodes[5].Nodes.Add("....x. SYN : " + ((tcpPacket.Syn)? 1 : 0)); xx = new int[4]; xx[0] = datagram.IHL * 8 + 110; xx[1] = datagram.IHL * 8 + 110; tn.Nodes[1].Nodes[5].Nodes[4].Tag = xx; tn.Nodes[1].Nodes[5].Nodes[4].ImageIndex = 3; tn.Nodes[1].Nodes[5].Nodes.Add(".....x FIN : " + ((tcpPacket.Fin)? 1 : 0)); xx = new int[4]; xx[0] = datagram.IHL * 8 + 111; xx[1] = datagram.IHL * 8 + 111; tn.Nodes[1].Nodes[5].Nodes[5].Tag = xx; tn.Nodes[1].Nodes[5].Nodes[5].ImageIndex = 3; tn.Nodes[1].Nodes.Add("Window : " + tcpPacket.WindowSize); xx = new int[4]; xx[0] = datagram.IHL * 8 + 112; xx[1] = datagram.IHL * 8 + 127; tn.Nodes[1].Nodes[6].Tag = xx; tn.Nodes[1].Nodes[6].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Checksum : " + tcpPacket.Checksum); xx = new int[4]; xx[0] = datagram.IHL * 8 + 128; xx[1] = datagram.IHL * 8 + 143; tn.Nodes[1].Nodes[7].Tag = xx; tn.Nodes[1].Nodes[7].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Urgent Pointer : " + tcpPacket.UrgentPointer); xx = new int[4]; xx[0] = datagram.IHL * 8 + 144; xx[1] = datagram.IHL * 8 + 159; tn.Nodes[1].Nodes[8].Tag = xx; tn.Nodes[1].Nodes[8].ImageIndex = 4; if (tcpPacket.DataOffset > 20) { tn.Nodes[1].Nodes.Add("Options + Padding : ....."); xx = new int[4]; xx[0] = datagram.IHL * 8 + 160; xx[1] = datagram.IHL * 8 + tcpPacket.DataOffset * 8 - 1; tn.Nodes[1].Nodes[9].Tag = xx; tn.Nodes[1].Nodes[9].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Data : " + "....."); xx = new int[4]; xx[0] = datagram.IHL * 8 + tcpPacket.DataOffset * 8; xx[1] = total * 8 - 1; tn.Nodes[1].Nodes[10].Tag = xx; tn.Nodes[1].Nodes[10].ImageIndex = 4; } else { tn.Nodes[1].Nodes.Add("Data : " + "....."); xx = new int[4]; xx[0] = datagram.IHL * 8 + tcpPacket.DataOffset * 8; xx[1] = total * 8 - 1; tn.Nodes[1].Nodes[9].Tag = xx; tn.Nodes[1].Nodes[9].ImageIndex = 4; } } else if (datagram.UpperProtocol == "Udp") { UdpDatagram udpDatagram = datagram.HandleUdpDatagram(); tn.Nodes.Add("Udp"); xx = new int[4]; xx[0] = datagram.IHL * 8; xx[1] = total * 8 - 1; tn.Nodes[1].Tag = xx; tn.Nodes[1].ImageIndex = 1; tn.Nodes[1].Nodes.Add("Source Port : " + udpDatagram.SourcePort.ToString() + " " + consts.GetTcpPorts(udpDatagram.SourcePort)); xx = new int[4]; xx[0] = datagram.IHL * 8; xx[1] = datagram.IHL * 8 + 15; tn.Nodes[1].Nodes[0].Tag = xx; tn.Nodes[1].Nodes[0].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Destination Port : " + udpDatagram.DestinationPort.ToString() + " " + consts.GetTcpPorts(udpDatagram.DestinationPort)); xx = new int[4]; xx[0] = datagram.IHL * 8 + 16; xx[1] = datagram.IHL * 8 + 31; tn.Nodes[1].Nodes[1].Tag = xx; tn.Nodes[1].Nodes[1].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Other Fields + Data : " + "....."); xx = new int[4]; xx[0] = datagram.IHL * 8 + 32; xx[1] = total * 8 - 1; tn.Nodes[1].Nodes[2].Tag = xx; tn.Nodes[1].Nodes[2].ImageIndex = 4; // tn.Nodes[15].Nodes.Add("Length : "+udpDatagram.Length); // tn.Nodes[15].Nodes.Add("Checksum : "+udpDatagram.Checksum); } else if (datagram.UpperProtocol == "ICMP") { IcmpPacket IPacket = datagram.HandleIcmpPacket(); tn.Nodes.Add("Icmp"); xx = new int[4]; xx[0] = datagram.IHL * 8; xx[1] = total * 8 - 1; tn.Nodes[1].Tag = xx; tn.Nodes[1].ImageIndex = 1; tn.Nodes[1].Nodes.Add("Type : " + consts.GetTypeForIcmp(IPacket.Type) + " {" + IPacket.Type.ToString() + "}"); xx = new int[4]; xx[0] = datagram.IHL * 8; xx[1] = datagram.IHL * 8 + 7; tn.Nodes[1].Nodes[0].Tag = xx; tn.Nodes[1].Nodes[0].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Code : " + consts.GetCodeForIcmp(IPacket.Type, IPacket.Code) + " {" + IPacket.Code.ToString() + "}"); xx = new int[4]; xx[0] = datagram.IHL * 8 + 8; xx[1] = datagram.IHL * 8 + 15; tn.Nodes[1].Nodes[1].Tag = xx; tn.Nodes[1].Nodes[1].ImageIndex = 4; tn.Nodes[1].Nodes.Add("Checksum : " + IPacket.Checksum.ToString()); xx = new int[4]; xx[0] = datagram.IHL * 8 + 16; xx[1] = datagram.IHL * 8 + 31; tn.Nodes[1].Nodes[2].Tag = xx; tn.Nodes[1].Nodes[2].ImageIndex = 4; if (IPacket.hasNextField) { int off = datagram.IHL * 8 + 32; int i = 0; for (i = 0; i < IPacket.GetFieldCount(); i++) { if (IPacket.GetFieldName(i) == "IP Address") { IPAddress ipa = new IPAddress(IPacket.GetField(i)); tn.Nodes[1].Nodes.Add(IPacket.GetFieldName(i) + " : " + ipa.ToString()); } else { tn.Nodes[1].Nodes.Add(IPacket.GetFieldName(i) + " : " + IPacket.GetField(i).ToString()); } xx = new int[4]; xx[0] = off; xx[1] = off + IPacket.GetFieldLengt(i) - 1; tn.Nodes[1].Nodes[3 + i].Tag = xx; tn.Nodes[1].Nodes[3 + i].ImageIndex = 4; off = off + IPacket.GetFieldLengt(i); } if (!IPacket.dataIsIp) { tn.Nodes[1].Nodes.Add("Data : " + "....."); xx = new int[4]; xx[0] = off; xx[1] = total * 8 - 1; tn.Nodes[1].Nodes[3 + i].Tag = xx; tn.Nodes[1].Nodes[3 + i].ImageIndex = 4; } else { tn.Nodes[1].Nodes.Add("Data : " + "(Has a Ip Packet)"); xx = new int[4]; xx[0] = off; xx[1] = total * 8 - 1; tn.Nodes[1].Nodes[3 + i].Tag = xx; tn.Nodes[1].Nodes[3 + i].ImageIndex = 1; tn.Nodes[1].Nodes[3 + i].Nodes.Add("Identification : " + HeaderParser.ToInt(IPacket.Data, 32, 16).ToString()); xx = new int[4]; xx[0] = off + 32; xx[1] = off + 47; tn.Nodes[1].Nodes[3 + i].Nodes[0].Tag = xx; tn.Nodes[1].Nodes[3 + i].Nodes[0].ImageIndex = 4; tn.Nodes[1].Nodes[3 + i].Nodes.Add("Protocol : " + HeaderParser.ToInt(IPacket.Data, 72, 8).ToString()); xx = new int[4]; xx[0] = off + 72; xx[1] = off + 79; tn.Nodes[1].Nodes[3 + i].Nodes[1].Tag = xx; tn.Nodes[1].Nodes[3 + i].Nodes[1].ImageIndex = 4; tn.Nodes[1].Nodes[3 + i].Nodes.Add("Source IP : " + IPAddress.Parse(IPv4Datagram.GetIPString(HeaderParser.ToUInt(IPacket.Data, 96, 32)))); xx = new int[4]; xx[0] = off + 96; xx[1] = off + 127; tn.Nodes[1].Nodes[3 + i].Nodes[2].Tag = xx; tn.Nodes[1].Nodes[3 + i].Nodes[2].ImageIndex = 4; tn.Nodes[1].Nodes[3 + i].Nodes.Add("Destination IP : " + IPAddress.Parse(IPv4Datagram.GetIPString(HeaderParser.ToUInt(IPacket.Data, 128, 32)))); xx = new int[4]; xx[0] = off + 128; xx[1] = off + 159; tn.Nodes[1].Nodes[3 + i].Nodes[3].Tag = xx; tn.Nodes[1].Nodes[3 + i].Nodes[3].ImageIndex = 4; tn.Nodes[1].Nodes[3 + i].Nodes.Add("Data : ....."); xx = new int[4]; xx[0] = off + HeaderParser.ToInt(IPacket.Data, 4, 4) * 32; xx[1] = total * 8; tn.Nodes[1].Nodes[3 + i].Nodes[4].Tag = xx; tn.Nodes[1].Nodes[3 + i].Nodes[4].ImageIndex = 4; } } else { tn.Nodes[1].Nodes.Add("Other Fields + Data : " + "....."); xx = new int[4]; xx[0] = datagram.IHL * 8 + 32; xx[1] = total * 8 - 1; tn.Nodes[1].Nodes[3].Tag = xx; tn.Nodes[1].Nodes[3].ImageIndex = 4; } } else //Other Protocols { ProtocolTemplate Others = datagram.HandleOthers(); tn.Nodes.Add(Others.ProtocolName); xx = new int[4]; xx[0] = datagram.IHL * 8; xx[1] = total * 8 - 1; tn.Nodes[1].Tag = xx; tn.Nodes[1].ImageIndex = 1; int [] yy = new int[2]; int off = datagram.IHL * 8; int i = 0; for (i = 0; i < Others.GetFieldCount(); i++) { tn.Nodes[1].Nodes.Add(Others.GetFieldName(i) + " : " + Others.GetField(i).ToString()); yy = Others.GetFieldLength(i); xx = new int[4]; xx[0] = off + yy[0]; xx[1] = off + yy[1] + yy[0] - 1; tn.Nodes[1].Nodes[i].Tag = xx; tn.Nodes[1].Nodes[i].ImageIndex = 4; } tn.Nodes[1].Nodes.Add("Data : ..... "); xx = new int[4]; xx[0] = off + yy[1]; xx[1] = total * 8 - 1; tn.Nodes[1].Nodes[i].Tag = xx; tn.Nodes[1].Nodes[i].ImageIndex = 4; } trv.Nodes.Add(tn); trv.ExpandAll(); trv.Update(); }
public DestinationUnreachableMsg(KaitaiStream p__io, IcmpPacket p__parent = null, IcmpPacket p__root = null) : base(p__io) { m_parent = p__parent; m_root = p__root; _read(); }
public int Ping(string host, int timeout) { double startTime = 0; int pingTime = -1; int pingDataSize = 4; // Ping packet payload, dummy data int packetSize = pingDataSize + 8; // Ping payload + ICMP header // Convert IP address string to something we can use IPEndPoint ipepServer; try { ipepServer = new IPEndPoint(IPAddress.Parse(host), 0); } catch (Exception e) { Debug.Log("Error parsing IP address: " + e.ToString()); return(-1); } EndPoint epServer = (ipepServer); Socket socket = new Socket(ipepServer.AddressFamily, SocketType.Dgram, ProtocolType.Icmp); socket.ReceiveTimeout = timeout; // Create packet IcmpPacket packet = new IcmpPacket(); packet.type = 8; // ICMP echo request packet.subCode = 0; packet.checkSum = 0; packet.identifier = 1; packet.sequenceNumber = 0; packet.data = new Byte[pingDataSize]; for (int i = 0; i < pingDataSize; i++) { packet.data[i] = (byte)'.'; } Byte [] icmpPacket = new Byte[packetSize]; // Populate buffer Serialize(packet, icmpPacket, pingDataSize); // Generate checksum UInt16 [] checksum = new UInt16[(int)((float)packetSize / 2)]; //Debug.Log("Checksum length is " + checksum.Length); int icmpPacketIndex = 0; for (int i = 0; i < checksum.Length; i++) { checksum[i] = BitConverter.ToUInt16(icmpPacket, icmpPacketIndex); icmpPacketIndex += 2; } packet.checkSum = generateChecksum(checksum, checksum.Length); // Repopulate packet with generated checksum Byte [] sendBuffer = new Byte[packetSize]; Serialize(packet, sendBuffer, pingDataSize); // Send the ping packet startTime = Network.time; if (socket.SendTo(sendBuffer, packetSize, 0, epServer) == 0) { Debug.Log("Socket Error cannot Send Packet"); } // Receive ping response Byte [] rcvBuffer = new Byte[256]; try { //socket.ReceiveFrom(rcvBuffer, ref epServer); socket.Receive(rcvBuffer); double stopTime = Network.time; pingTime = (int)((stopTime - startTime) * 1000); //Debug.Log("Reply from "+epServer.ToString()+" containing "+rcvBytes+" bytes in "+pingTime+" ms"); } catch (SocketException e) { Debug.Log("Socket error: " + e.ToString()); } catch (Exception e) { Debug.Log("Exception occured when receiving " + e.ToString()); } socket.Close(); return(pingTime); }
public void Execute(string host, int dataLength, int pingCount, int timeout, int waitTimeBetweenAttempts) { if (string.IsNullOrEmpty(host)) { ThrowHelper.ThrowArgumentNullException("host"); } if (dataLength < 0) { ThrowHelper.ThrowArgumentOutOfRangeException("dataLength"); } if (pingCount < 0) { ThrowHelper.ThrowArgumentOutOfRangeException("pingCount"); } if (timeout < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("timeout"); } this.IsFinished = false; IPHostEntry hostByName = null; int bytesReceived = 0; int tickCount = 0; int pingStop = 0; mPingLoop = 0; try { hostByName = Dns.GetHostEntry(host); } catch (Exception) { IsFinished = true; OnPingResult(PingResultEnum.HostNotFoundError); OnPingResult(PingResultEnum.Finished); return; } IPEndPoint remoteEP = new IPEndPoint(hostByName.AddressList[0], 0); this.mRemoteIpAddress = remoteEP.Address; EndPoint localPoint = new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList[0], 0); IcmpPacket packet = new IcmpPacket(); packet.Type = ICMP_ECHO; packet.SubCode = 0; packet.CheckSum = Convert.ToUInt16(0); packet.Identifier = Convert.ToUInt16(45); packet.SequenceNumber = Convert.ToUInt16(0); packet.Data = new byte[dataLength]; for (int i = 0; i <= dataLength - 1; i++) { packet.Data[i] = 35; // # } int packetSize = dataLength + 8; byte[] buffer = new byte[packetSize]; int res = this.CreatePacket(packet, buffer, packetSize, dataLength); if (res == SOCKET_ERROR) { IsFinished = true; OnPingResult(PingResultEnum.BadPacketError); OnPingResult(PingResultEnum.Finished); } else { ushort[] checksumBuffer = new ushort[(Convert.ToInt32(Math.Ceiling((double)(Convert.ToDouble(res) / 2.0))) - 1) + 1]; int index = 0; if (checksumBuffer.Length > 0) { for (int i = 0; i <= checksumBuffer.Length - 1; i++) { checksumBuffer[i] = BitConverter.ToUInt16(buffer, index); index += 2; } } packet.CheckSum = this.CheckSum(checksumBuffer); byte[] dataBuffer = new byte[packetSize + 1]; if (this.CreatePacket(packet, dataBuffer, packetSize, dataLength) == SOCKET_ERROR) { IsFinished = true; OnPingResult(PingResultEnum.BadPacketError); OnPingResult(PingResultEnum.Finished); } else { long totalTime = 0L; this.mPacketSent = 0; this.mPacketReceived = 0; this.mMinimumPingTime = int.MaxValue; this.mMaximumPingTime = int.MinValue; do { bool receivedFlag = false; using (Socket pingSocket = new Socket(mRemoteIpAddress.AddressFamily, SocketType.Raw, ProtocolType.Icmp)) { pingSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout); pingSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout); byte[] receiveBuffer = new byte[MAX_PACKET_SIZE]; tickCount = Environment.TickCount; this.mPacketSent++; if (pingSocket.SendTo(dataBuffer, packetSize, SocketFlags.None, remoteEP) == SOCKET_ERROR) { OnPingResult(PingResultEnum.SocketError); } else { bytesReceived = 0; while (!receivedFlag) { try { bytesReceived = pingSocket.ReceiveFrom(receiveBuffer, MAX_PACKET_SIZE, SocketFlags.None, ref localPoint); } catch (Exception) { OnPingResult(PingResultEnum.RequestTimeout); receivedFlag = false; break; } if (bytesReceived == -1) { OnPingResult(PingResultEnum.NoResponse); receivedFlag = false; break; } if (bytesReceived > 0) { receivedFlag = true; pingStop = Environment.TickCount - tickCount; if (pingStop > timeout) { OnPingResult(PingResultEnum.RequestTimeout); receivedFlag = false; Thread.Sleep(DEFAULT_WAITTIME_ATTEMPTS); } else { OnPingResult(bytesReceived - 28, pingStop); } break; } } if (receivedFlag) { this.mPacketReceived++; totalTime += pingStop; if (pingStop > this.mMaximumPingTime) { this.mMaximumPingTime = pingStop; } if (pingStop < this.mMinimumPingTime) { this.mMinimumPingTime = pingStop; } } } mPingLoop++; pingSocket.Shutdown(SocketShutdown.Both); pingSocket.Close(); receiveBuffer = null; if (receivedFlag & (mPingLoop < pingCount)) { Thread.Sleep(DEFAULT_WAITTIME_ATTEMPTS); } } }while (mPingLoop < pingCount); this.mPacketLost = this.mPacketSent - this.mPacketReceived; if (this.mPacketReceived == 0) { this.mPacketLostPercent = 0.0; this.mMinimumPingTime = 0; this.mMaximumPingTime = 0; this.mAveragePingTime = 0; } else { this.mPacketLostPercent = (((double)(this.mPacketSent - this.mPacketReceived)) / ((double)this.mPacketSent)) * 100.0; this.mAveragePingTime = Convert.ToInt32((double)(((double)totalTime) / ((double)this.mPacketSent))); } buffer = null; checksumBuffer = null; dataBuffer = null; packet.Data = null; packet = null; IsFinished = true; OnPingResult(PingResultEnum.Finished); } } }
public bool DoRequest() { //backData.Clear(); if (MyIPAddress.AddressFamily == AddressFamily.InterNetwork) { //传入是正确的Ipv4格式 EndPoint hostEndpoint = (EndPoint) new IPEndPoint(MyIPAddress, 1025); //循环5次发送icmp包的操作 for (int i = 0; i < 5; i++) { RequestObj request = new RequestObj { CreateTime = DateTime.Now };//创建一个请求对象 //CreateTime = DateTime.Now; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start();//记录耗时 int Datasize = 4; int Packetsize = 8 + Datasize; Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); EndPoint clientep = (EndPoint) new IPEndPoint(IPAddress.Parse("127.0.0.1"), 30); IcmpPacket packet = new IcmpPacket(8, 0, 0, 45, 0, Datasize); Byte[] myBuffer = new Byte[Packetsize]; int index = packet.CountByte(myBuffer); if (index != Packetsize) { //exception.Text = "报文出现问题"; //backData.Add("报文出现问题", "-1"); //IcmpReturn information = new IcmpReturn //{ // Color = "0"//错误 //}; //string backJson = JsonConvert.SerializeObject(information); //backData.Add("1", backJson); //Color = "0"; request.Color = "0"; request.TimeCost = (short)stopwatch.ElapsedMilliseconds; Requests.Add(request); return(false); } int Cksum_buffer_length = (int)Math.Ceiling(((Double)index) / 2); UInt16[] Cksum_buffer = new UInt16[Cksum_buffer_length]; int Icmp_header_buffer_index = 0; for (int j = 0; j < Cksum_buffer_length; j++) { //把两个byte转化为一个uint16 Cksum_buffer[j] = BitConverter.ToUInt16(myBuffer, Icmp_header_buffer_index); Icmp_header_buffer_index += 2; } //保存校验和 packet.CheckSum = IcmpPacket.SumOfCheck(Cksum_buffer); //将报文转化为数据包 Byte[] Senddata = new Byte[Packetsize]; index = packet.CountByte(Senddata); //报文出错 if (index != Packetsize) { //exception.Text = "报文出错2"; //backData.Add("报文出现问题", "0"); //Color = "0"; request.Color = "0"; request.TimeCost = (short)stopwatch.ElapsedMilliseconds; //string backJson = JsonConvert.SerializeObject(information); //backData.Add("1", backJson); Requests.Add(request); return(false); } int Nbytes = 0; //系统计时 int starttime = Environment.TickCount; //发送数据包 try { Nbytes = socket.SendTo(Senddata, Packetsize, SocketFlags.None, hostEndpoint); if (Nbytes == -1) { //exception.Text = "无法传送"; //backData.Add("访问被拒绝", "403"); //IcmpReturn information = new IcmpReturn //{ // Color = "0"//错误 //}; //string backJson = JsonConvert.SerializeObject(information); //backData.Add(i.ToString(), backJson); //Color = "0";//访问被拒绝 request.Color = "0"; request.TimeCost = (short)stopwatch.ElapsedMilliseconds; //TimeCost = (short)stopwatch.ElapsedMilliseconds; Requests.Add(request); return(false); } Byte[] Recewivedata = new Byte[256]; Nbytes = 0; //int Timeout = 0; int timeconsume = 0; while (true) { //socket.Blocking = false; // 这里设置站点超时判断 //socket.ReceiveTimeout = 1000; socket.ReceiveTimeout = request.OverTime; try { Nbytes = socket.ReceiveFrom(Recewivedata, 256, SocketFlags.None, ref hostEndpoint); } catch (Exception e) { //服务器连接失败一类的异常 Nbytes = -1; //Debug.WriteLine(e.ToString()); DBHelper.InsertErrorLog(e.InnerException); } if (Nbytes == -1) { //exception.Text = "主机未响应"; //backData.Add("主机未响应", "404"); //IcmpReturn information = new IcmpReturn //{ // Color = "0"//错误 //}; request.Color = "0"; //string backJson = JsonConvert.SerializeObject(information); //backData.Add(i.ToString(), backJson); //return backData; request.TimeCost = (short)stopwatch.ElapsedMilliseconds; Requests.Add(request); break; } else if (Nbytes > 0) { timeconsume = System.Environment.TickCount - starttime; //得到与发送间隔时间 //exception.Text += "reply from: " + hostep4.ToString() + " In " + timeconsume + "ms: bytes Received" + Nbytes + "\r\n"; //IcmpReturn information = new IcmpReturn //{ // Time = timeconsume.ToString(), // TTL = socket.Ttl.ToString(), // Bytes = Nbytes.ToString(), // Color = "1" //}; //string backJson = JsonConvert.SerializeObject(information); //backData.Add(i.ToString(), backJson); request.Color = "1"; request.TimeCost = (short)stopwatch.ElapsedMilliseconds; Requests.Add(request); break; } timeconsume = Environment.TickCount - starttime; if (timeconsume > 1000) { //exception.Text = "time out"; //backData.Add("超时", "404"); //IcmpReturn information = new IcmpReturn //{ // Color = "-1"//超时 //}; request.Color = "-1"; //string backJson = JsonConvert.SerializeObject(information); //backData.Add(i.ToString(), backJson); //return backData; request.TimeCost = (short)stopwatch.ElapsedMilliseconds; Requests.Add(request); break; } } socket.Dispose(); } catch (Exception ex) { string s = ex.Message; //IcmpReturn information = new IcmpReturn //{ // Color = "0"//超时 //}; request.Color = "0"; //string backJson = JsonConvert.SerializeObject(information); //backData.Add(i.ToString(), backJson); request.TimeCost = (short)stopwatch.ElapsedMilliseconds; request.ErrorException = ex; Requests.Add(request); return(false); } } return(true); } else { //backData.Add("ip地址不规范", "-1"); //IcmpReturn information = new IcmpReturn //{ // Color = "0"//错误 //}; RequestObj request = new RequestObj { CreateTime = DateTime.Now };//创建一个请求对象 request.Color = "0"; request.TimeCost = 0; return(false); } }
public EchoMsg(KaitaiStream p__io, IcmpPacket p__parent = null, IcmpPacket p__root = null) : base(p__io) { m_parent = p__parent; m_root = p__root; _read(); }
// Move contents of packet to a byte array (buffer). pingDataSize defines how large // packet.data is. private void Serialize(IcmpPacket packet, Byte[] buffer, Int32 pingDataSize ) { buffer[0] = packet.type; buffer[1] = packet.subCode; Array.Copy( BitConverter.GetBytes(packet.checkSum), 0, buffer, 2, 2 ); Array.Copy( BitConverter.GetBytes(packet.identifier), 0, buffer, 4, 2 ); Array.Copy( BitConverter.GetBytes(packet.sequenceNumber), 0, buffer, 6, 2 ); Array.Copy( packet.data, 0, buffer, 8, pingDataSize ); }
/// <summary> /// Log a new ICMP packet. /// </summary> /// <param name="packet"> /// The packet to log. /// </param> public void LogPacket(IcmpPacket packet) { lock (m_logger.XmlWriter) { // <IcmpHeader> m_logger.XmlWriter.WriteStartElement("IcmpHeader"); m_logger.XmlWriter.WriteElementString("Type", packet.MessageType.ToString()); m_logger.XmlWriter.WriteElementString("Checksum", packet.Checksum.ToString()); #region Specific ICMP Types switch (packet.MessageType) { case IcmpMessageType.DestinationUnreachable: IcmpDestinationUnreachable option1 = new IcmpDestinationUnreachable(packet); m_logger.XmlWriter.WriteElementString("Code", option1.Code.ToString()); break; case IcmpMessageType.Echo: IcmpEcho option2 = new IcmpEcho(packet); m_logger.XmlWriter.WriteElementString("Identifier", option2.Identifier.ToString()); m_logger.XmlWriter.WriteElementString("SequenceNumber", option2.SequenceNumber.ToString()); m_logger.XmlWriter.WriteElementString("DataLength", (option2.Data != null ? option2.Data.Length : 0) + " bytes"); m_logger.XmlWriter.WriteElementString("Data", (option2.Data != null ? System.Text.ASCIIEncoding.ASCII.GetString(option2.Data) : string.Empty)); break; case IcmpMessageType.EchoReply: IcmpEcho option3 = new IcmpEcho(packet); m_logger.XmlWriter.WriteElementString("Identifier", option3.Identifier.ToString()); m_logger.XmlWriter.WriteElementString("SequenceNumber", option3.SequenceNumber.ToString()); m_logger.XmlWriter.WriteElementString("DataLength", (option3.Data != null ? option3.Data.Length : 0) + " bytes"); m_logger.XmlWriter.WriteElementString("Data", (option3.Data != null ? System.Text.ASCIIEncoding.ASCII.GetString(option3.Data) : string.Empty)); break; case IcmpMessageType.ParameterProblem: IcmpParameterProblem option4 = new IcmpParameterProblem(packet); m_logger.XmlWriter.WriteElementString("Pointer", option4.ErrorPointer.ToString()); break; case IcmpMessageType.Redirect: IcmpRedirect option5 = new IcmpRedirect(packet); m_logger.XmlWriter.WriteElementString("Gateway", option5.GatewayAddress.ToString()); break; case IcmpMessageType.SourceQuench: break; case IcmpMessageType.TimeExceeded: break; case IcmpMessageType.TimeStamp: break; case IcmpMessageType.TimestampReply: break; } #endregion m_logger.XmlWriter.WriteEndElement(); // </IcmpHeader> } }