public void CollectStatWhenGiven2ip2icmp1tcp5udpPacketsThenCountOfPacketsIsRight() { NetworkPacket[] packets = new NetworkPacket[10]; packets[0] = new IPPacket(); packets[1] = new IPPacket(); packets[2] = new ICMPPacket(); packets[3] = new ICMPPacket(); packets[4] = new TCPPacket(); packets[5] = new UDPPacket(); packets[6] = new UDPPacket(); packets[7] = new UDPPacket(); packets[8] = new UDPPacket(); packets[9] = new UDPPacket(); Firewall fw = new Firewall(new FilterMock(), new DistributorMock()); CollectStatCommand clltStat = new CollectStatCommand(); Assert.AreEqual(fw.Statistics["ip"], 0); Assert.AreEqual(fw.Statistics["icmp"], 0); Assert.AreEqual(fw.Statistics["tcp"], 0); Assert.AreEqual(fw.Statistics["udp"], 0); Assert.AreEqual(fw.Statistics["total"], 0); foreach (var packet in packets) { clltStat.DoWithPacket(fw, packet); } Assert.AreEqual(fw.Statistics["ip"], 2); Assert.AreEqual(fw.Statistics["icmp"], 2); Assert.AreEqual(fw.Statistics["tcp"], 1); Assert.AreEqual(fw.Statistics["udp"], 5); Assert.AreEqual(fw.Statistics["total"], 10); }
public IPPacket(ref byte[] Packet) : base() { try { Version = (byte)(Packet[0] >> 4); HeaderLength = (byte)((Packet[0] & 0x0F) * 4); TypeOfService = Packet[1]; TotalLength = (ushort)System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 2)); Identification = (ushort)System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 4)); Flags = (byte)((Packet[6] & 0xE0) >> 5); FragmentOffset = (ushort)(System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 6)) & 0x1FFF); TimeToLive = Packet[8]; Protocol = Packet[9]; HeaderChecksum = (ushort)(System.Net.IPAddress.NetworkToHostOrder(System.BitConverter.ToInt16(Packet, 10))); SourceAddress = new System.Net.IPAddress(System.BitConverter.ToInt32(Packet, 12) & 0x00000000FFFFFFFF); DestinationAddress = new System.Net.IPAddress(System.BitConverter.ToInt32(Packet, 16) & 0x00000000FFFFFFFF); PacketData = new byte[TotalLength - HeaderLength]; System.Buffer.BlockCopy(Packet, HeaderLength, PacketData, 0, PacketData.Length); } catch { } switch (Protocol) { case 1: ICMP = new ICMPPacket(ref PacketData); break; case 6: TCP = new TCPPacket(ref PacketData); break; case 17: UDP = new UDPPacket(ref PacketData); break; } }
internal static void UpdateIcmpNode(TreeView treeView, ICMPPacket icmpPacket) { TreeNode icmpNode = treeView.Nodes["ICMP"]; if (icmpNode == null) { icmpNode = AddIcmpNode(treeView); } icmpNode.Text = String.Format("Internet Control Message Protocol: {0}", ICMPMessage.getDescription(icmpPacket.MessageKey)); icmpNode.Nodes["Type"].Text = String.Format("Type: {0}", icmpPacket.MessageType); icmpNode.Nodes["Code"].Text = String.Format("Code: {0}", icmpPacket.MessageCode); icmpNode.Nodes["Checksum"].Text = String.Format("Checksum: 0x{0:X4} ({1})", icmpPacket.ICMPChecksum, icmpPacket.ValidICMPChecksum ? "correct" : "incorrect"); if (icmpPacket.IsEchoRequestOrReply) { if (icmpNode.Nodes["Id"] == null) { icmpNode.Nodes.Add("Id", String.Empty); icmpNode.Nodes.Add("SeqNumber", String.Empty); } icmpNode.Nodes["Id"].Text = String.Format("Identifier: {0}", icmpPacket.Id); icmpNode.Nodes["SeqNumber"].Text = String.Format("Sequence number: {0}", icmpPacket.SequenceNumber); } else if (icmpNode.Nodes["Id"] != null) { icmpNode.Nodes["Id"].Remove(); icmpNode.Nodes["SeqNumber"].Remove(); } }
void GivenIcmpPacketWithIPDstIs1_1_1_1AndOtherAddr() { icmpPackets = new ICMPPacket[2]; ICMPPacket packetWithIPDst1_1_1_1 = new ICMPPacket(); ICMPPacket otherPacket = new ICMPPacket(); packetWithIPDst1_1_1_1.SrcIP = new NetworkAddress("1.2.3.4"); otherPacket.SrcIP = new NetworkAddress("1.2.3.4"); otherPacket.DstIP = new NetworkAddress("4.3.2.1"); packetWithIPDst1_1_1_1.DstIP = new NetworkAddress("1.1.1.1"); icmpPackets[0] = packetWithIPDst1_1_1_1; icmpPackets[1] = otherPacket; }
// main routine public override PacketMainReturnType interiorMain(ref Packet in_packet) { LogEvent le; // if the packet is ICMPv4 if (in_packet.GetHighestLayer() == Protocol.ICMP) { ICMPPacket packet = (ICMPPacket)in_packet; // check if the packet is allowed and deny all is false if (isAllowed(packet.Type.ToString(), packet.Code.ToString(), 4) && !data.DenyIPv4) { return(PacketMainReturnType.Allow); } // else, log and drop it else { PacketMainReturnType pmr = PacketMainReturnType.Drop; if (data.Log) { pmr |= PacketMainReturnType.Log; le = new LogEvent(String.Format(multistring.GetString("ICMPv4 was dropped"), packet.SourceIP.ToString(), packet.DestIP.ToString()), this); le.PMR = PacketMainReturnType.Log | PacketMainReturnType.Drop; LogCenter.Instance.LogEvent(le); } return(pmr); } } // if the packet is ICMPv6 if (in_packet.GetHighestLayer() == Protocol.ICMPv6) { ICMPv6Packet packet = (ICMPv6Packet)in_packet; if ((isAllowed(packet.Type.ToString(), packet.Code.ToString(), 6) && !data.DenyIPv6) && isDeniedNDP(packet)) { return(PacketMainReturnType.Allow); } else { PacketMainReturnType pmr = PacketMainReturnType.Drop; if (data.Log) { pmr |= PacketMainReturnType.Log; le = new LogEvent(String.Format(multistring.GetString("ICMPv6 was dropped"), packet.SourceIP.ToString(), packet.DestIP.ToString()), this); le.PMR = PacketMainReturnType.Log | PacketMainReturnType.Drop; LogCenter.Instance.LogEvent(le); } return(pmr); } } return(PacketMainReturnType.Allow); }
// main routine public override PacketMainReturn interiorMain(ref Packet in_packet) { // if the packet is ICMPv4 if (in_packet.GetHighestLayer() == Protocol.ICMP) { ICMPPacket packet = (ICMPPacket)in_packet; // check if the packet is allowed and deny all is false if (isAllowed(packet.Type.ToString(), packet.Code.ToString(), 4) && !data.DenyIPv4) { return(null); } // else, log and drop it else { PacketMainReturn pmr; pmr = new PacketMainReturn(this); pmr.returnType = PacketMainReturnType.Drop; if (data.Log) { pmr.returnType |= PacketMainReturnType.Log; pmr.logMessage = "ICMP from " + packet.SourceIP.ToString() + " for " + packet.DestIP.ToString() + " was dropped."; } return(pmr); } } // if the packet is ICMPv6 if (in_packet.GetHighestLayer() == Protocol.ICMPv6) { ICMPv6Packet packet = (ICMPv6Packet)in_packet; if ((isAllowed(packet.Type.ToString(), packet.Code.ToString(), 6) && !data.DenyIPv6) && isDeniedNDP(packet)) { return(null); } else { PacketMainReturn pmr; pmr = new PacketMainReturn(this); pmr.returnType = PacketMainReturnType.Drop; if (data.Log) { pmr.returnType |= PacketMainReturnType.Log; pmr.logMessage = "ICMPv6 from " + packet.SourceIP.ToString() + " for " + packet.DestIP.ToString() + " was dropped."; } return(pmr); } } return(null); }
public void TestICMPConverterFromBytesToObject() { byte[] binPacket = new byte[ICMPPacket.Size]; //Source MAC binPacket[0] = 0x11; binPacket[1] = 0x22; binPacket[2] = 0x33; binPacket[3] = 0x44; binPacket[4] = 0x55; binPacket[5] = 0x66; //Destination MAC binPacket[6] = 0x66; binPacket[7] = 0x55; binPacket[8] = 0x44; binPacket[9] = 0x33; binPacket[10] = 0x22; binPacket[11] = 0x11; //Source IP binPacket[12] = 127; binPacket[13] = 0; binPacket[14] = 0; binPacket[15] = 1; //Destination IP binPacket[16] = 1; binPacket[17] = 1; binPacket[18] = 1; binPacket[19] = 1; //Type binPacket[20] = 10; //Code binPacket[21] = 2; //Data binPacket[22] = 1; binPacket[23] = 2; ICMPPacket packet = new ICMPPacket(); packet.SrcMAC = new PhysicalAddress(new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 }); packet.DstMAC = new PhysicalAddress(new byte[] { 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }); packet.SrcIP = new NetworkAddress("127.0.0.1"); packet.DstIP = new NetworkAddress("1.1.1.1"); packet.Type = 10; packet.Code = 2; packet.Data[0] = 1; packet.Data[1] = 2; IcmpPacketConverter converter = new IcmpPacketConverter(); ICMPPacket convertedPacket = (ICMPPacket) converter.ConvertPacket(binPacket); Assert.AreEqual(packet, convertedPacket); }
/// <summary> /// Initialize the Network Stack to prepare it for operation. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown on fatal error (contact support).</exception> public static void Init() { AddressMap = new TempDictionary <NetworkDevice>(); // VMT Scanner issue workaround ARPPacket.VMTInclude(); ARPPacket_Ethernet.VMTInclude(); ARPReply_Ethernet.VMTInclude(); ARPRequest_Ethernet.VMTInclude(); ICMPPacket.VMTInclude(); ICMPEchoReply.VMTInclude(); ICMPEchoRequest.VMTInclude(); UDPPacket.VMTInclude(); //TCPPacket.VMTInclude(); }
public void TestCopyICMPPacket() { ICMPPacket packetSrc = new ICMPPacket(); ICMPPacket packetDst = new ICMPPacket(); packetSrc.SrcMAC = new PhysicalAddress(new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66 }); packetSrc.DstMAC = new PhysicalAddress(new byte[] { 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }); packetSrc.SrcIP = new NetworkAddress("127.0.0.1"); packetSrc.DstIP = new NetworkAddress("1.1.1.1"); packetSrc.Type = 10; packetSrc.Code = 1; packetSrc.Data[0] = 1; packetSrc.Data[1] = 0x33; packetSrc.Copy(packetDst); Assert.AreEqual(packetSrc, packetDst); Assert.AreNotSame(packetSrc, packetDst); }
void Given5UdpPacketsAnd2IcmpPackets() { udpPackets = new UDPPacket[5]; UDPPacket udpPacket = new UDPPacket(); udpPacket.SrcIP = new NetworkAddress("1.2.3.4"); udpPacket.DstIP = new NetworkAddress("4.3.2.1"); udpPackets[0] = udpPacket; udpPackets[1] = udpPacket; udpPackets[2] = udpPacket; udpPackets[3] = udpPacket; udpPackets[4] = udpPacket; icmpPackets = new ICMPPacket[2]; icmpPackets[0] = new ICMPPacket(); icmpPackets[1] = new ICMPPacket(); icmpPackets[0].SrcIP = new NetworkAddress("1.2.3.4"); icmpPackets[0].DstIP = new NetworkAddress("4.3.2.1"); icmpPackets[1].SrcIP = new NetworkAddress("1.2.3.4"); icmpPackets[1].DstIP = new NetworkAddress("4.3.2.1"); }
public void TestICMPPacket() { SharpNet.OnReceiveICMPPacketHandler Handler = async(ICMPPacket Packet) => { ICMPPacket echo = new ICMPPacket(Packet.Data); echo.Type = 0; echo.PingId = Packet.PingId; echo.PingSeq = Packet.PingSeq; echo.DestIP = Packet.SourceIP; echo.SourceIP = Packet.DestIP; await net.SendIPPacketAsync(echo); }; net.OnReceiveICMPPacket += Handler; //Task.Delay(30000).Wait(); for (int i = 0; i < 10; i++) { var result = ping.Send(RemoteIP, 100); Assert.AreEqual(IPStatus.Success, result.Status, "Timeout occured"); Trace.WriteLine(string.Format("{0} ms delay", result.RoundtripTime)); } net.OnReceiveICMPPacket -= Handler; }
// main routine public override PacketMainReturnType interiorMain(ref Packet in_packet) { PacketMainReturnType pmr; LogEvent le; // check it the packet is, or contains, IP if (in_packet.ContainsLayer(Protocol.IP)) { // create a temp IPPacket obj and // check the IP address IPPacket temp = (IPPacket)in_packet; if (!isIPAllowed(temp.SourceIP)) { pmr = PacketMainReturnType.Drop; return(pmr); } } // simple sanity check to dump the ipcache if it gets too large. // this does not effect the blockcache of banned IPs if ((ipcache.Count) > 500) { ipcache.Clear(); } // TCP incoming packets if (in_packet.GetHighestLayer() == Protocol.TCP) { TCPPacket packet = ((TCPPacket)in_packet); packet.PacketTime = DateTime.UtcNow; // if it's inbound and the SYN flag is set if (!packet.Outbound && packet.SYN && !packet.ACK) { // first packet init if (TCPprevious_packet == null) { TCPprevious_packet = packet; } // if the IP hasn't been logged yet if (!(ipcache.ContainsKey(packet.SourceIP))) { ipcache.Add(packet.SourceIP, 1); } // if the ipcache contains the ip else if (ipcache.ContainsKey(packet.SourceIP)) { // increment the packet count if they're coming in fast if ((packet.PacketTime - TCPprevious_packet.PacketTime).TotalMilliseconds <= data.dos_threshold) { ipcache[packet.SourceIP] = (ipcache[packet.SourceIP]) + 1; } else { ipcache[packet.SourceIP] = 1; } // check if this packet = previous, if the packet count is > 50, // and if the time between sent packets is less than the threshhold if (packet.SourceIP.Equals(TCPprevious_packet.SourceIP) && ((ipcache[packet.SourceIP]) > 50) && (packet.PacketTime - TCPprevious_packet.PacketTime).TotalMilliseconds <= data.dos_threshold) { pmr = PacketMainReturnType.Drop | PacketMainReturnType.Log | PacketMainReturnType.Popup; le = new LogEvent(String.Format(multistring.GetString("DoS Log"), packet.SourceIP.ToString()), this); le.PMR = PacketMainReturnType.Drop | PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); data.BlockCache.Add(packet.SourceIP, new BlockedIP(packet.SourceIP, DateTime.UtcNow, "DoS Attempt")); return(pmr); } } TCPprevious_packet = packet; } } // fraggle attack mitigation if (in_packet.GetHighestLayer() == Protocol.UDP) { UDPPacket packet = ((UDPPacket)in_packet); packet.PacketTime = DateTime.UtcNow; // if it's inbound if (!(packet.Outbound)) { // add IP to cache or increment packet count if (!(ipcache.ContainsKey(packet.SourceIP))) { ipcache.Add(packet.SourceIP, 1); } else { ipcache[packet.SourceIP] = (ipcache[packet.SourceIP]) + 1; } // if the packet header is empty, headed towards port (7,13,19,17), and count > 50, // then it's probably a fraggle attack if (packet.isEmpty() && packet.DestPort.Equals(7) || packet.DestPort.Equals(13) || packet.DestPort.Equals(19) || packet.DestPort.Equals(17) && (ipcache[packet.SourceIP]) > 50) { pmr = PacketMainReturnType.Drop | PacketMainReturnType.Log | PacketMainReturnType.Popup; le = new LogEvent(String.Format(multistring.GetString("Fraggle Log"), packet.SourceIP.ToString()), this); le.PMR = PacketMainReturnType.Drop | PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); data.BlockCache.Add(packet.SourceIP, new BlockedIP(packet.SourceIP, DateTime.UtcNow, "Fraggle Attempt")); return(pmr); } } } // smurf attack mitigation if (in_packet.GetHighestLayer() == Protocol.ICMP) { ICMPPacket packet = ((ICMPPacket)in_packet); packet.PacketTime = DateTime.UtcNow; if (!(packet.Outbound)) { // init the previous packet if (ICMPprevious_packet == null) { ICMPprevious_packet = packet; } // add IP to cache or increment packet count if (!(ipcache.ContainsKey(packet.SourceIP))) { ipcache.Add(packet.SourceIP, 1); } // if the packet is >= threshold after the previous and it's the same packet, clear up the cache else if ((packet.PacketTime.Millisecond - ICMPprevious_packet.PacketTime.Millisecond) >= data.dos_threshold && packet.Equals(ICMPprevious_packet)) { ipcache[packet.SourceIP] = 1; } // if the packet is coming in quickly, add it to the packet count else if ((packet.PacketTime.Millisecond - ICMPprevious_packet.PacketTime.Millisecond) <= data.dos_threshold) { ipcache[packet.SourceIP] = (ipcache[packet.SourceIP]) + 1; } // if the packet is an echo reply and the IP source // is the same as localhost and the time between packets is <= threshhold and // there are over 50 accumulated packets, it's probably a smurf attack if (packet.Type.ToString().Equals("0") && packet.Code.ToString().Equals("0") && isLocalIP(packet.SourceIP) && (packet.PacketTime.Millisecond - ICMPprevious_packet.PacketTime.Millisecond) <= data.dos_threshold && ipcache[packet.SourceIP] > 50) { pmr = PacketMainReturnType.Drop | PacketMainReturnType.Log | PacketMainReturnType.Popup; le = new LogEvent(String.Format(multistring.GetString("Smurf Log"), packet.SourceIP.ToString()), this); le.PMR = PacketMainReturnType.Drop | PacketMainReturnType.Log | PacketMainReturnType.Popup; LogCenter.Instance.LogEvent(le); data.BlockCache.Add(packet.SourceIP, new BlockedIP(packet.SourceIP, DateTime.UtcNow, "Smurf Attempt")); return(pmr); } ICMPprevious_packet = packet; } } return(PacketMainReturnType.Allow); }
private void DisplayPacketData(Packet packet) { packetsCount++; packetsDictionary.AddOrUpdate(packetsCount, packet, (i, p) => p); ListViewItem packetItem; if (packet is ARPPacket) { ARPPacket arpPacket = (ARPPacket)packet; packetItem = ListViewVisualizer.GenerateListViewItem( Color.LightPink, packetsCount.ToString(), TreeViewVisualizer.GetHyphenatedHwAddress(arpPacket.ARPSenderHwAddress), String.Empty, String.Empty, TreeViewVisualizer.GetHyphenatedHwAddress(arpPacket.ARPTargetHwAddress), String.Empty, String.Empty, "ARP", arpPacket.ToString()); } else if (packet is ICMPPacket) { ICMPPacket icmpPacket = (ICMPPacket)packet; packetItem = ListViewVisualizer.GenerateListViewItem( Color.Thistle, packetsCount.ToString(), icmpPacket.SourceAddress.ToString(), DnsTable.GetHostByAddress(icmpPacket.SourceAddress), String.Empty, icmpPacket.DestinationAddress.ToString(), DnsTable.GetHostByAddress(icmpPacket.DestinationAddress), String.Empty, "ICMP", icmpPacket.ToString()); } else if (packet is TCPPacket) { TCPPacket tcpPacket = (TCPPacket)packet; packetItem = ListViewVisualizer.GenerateListViewItem( Color.LightSkyBlue, packetsCount.ToString(), tcpPacket.SourceAddress.ToString(), DnsTable.GetHostByAddress(tcpPacket.SourceAddress), tcpPacket.SourcePort.ToString(), tcpPacket.DestinationAddress.ToString(), DnsTable.GetHostByAddress(tcpPacket.DestinationAddress), tcpPacket.DestinationPort.ToString(), "TCP", tcpPacket.ToString()); } else if (packet is UDPPacket) { UDPPacket udpPacket = (UDPPacket)packet; packetItem = ListViewVisualizer.GenerateListViewItem( Color.LemonChiffon, packetsCount.ToString(), udpPacket.SourceAddress.ToString(), DnsTable.GetHostByAddress(udpPacket.SourceAddress), udpPacket.SourcePort.ToString(), udpPacket.DestinationAddress.ToString(), DnsTable.GetHostByAddress(udpPacket.DestinationAddress), udpPacket.DestinationPort.ToString(), "UDP", udpPacket.ToString()); } else { packetItem = ListViewVisualizer.GenerateListViewItem( Color.Linen, packetsCount.ToString(), String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, String.Empty, "unknown", String.Empty); } AddListViewItemDelegate addListViewItemDelegate = new AddListViewItemDelegate(ListViewVisualizer.AddListViewItem); listViewPackets.Invoke(addListViewItemDelegate, new object[] { packetItem, listViewPackets }); ShowDisplayedPacketsCountDelegate showDisplayedPacketsDelegate = new ShowDisplayedPacketsCountDelegate(StatusStripVisualizer.SetLabelText); statusStrip.Invoke(showDisplayedPacketsDelegate, new object[] { toolStripStatusLabelPacketsInfo.Name, String.Format("|Displayed packets: {0}", packetsCount), statusStrip }); if (packetsCount == 1) { UpdateTreeViewDelegate updateTreeViewDelegate = new UpdateTreeViewDelegate(TreeViewVisualizer.UpdateTreeView); treeViewPacketInfo.Invoke(updateTreeViewDelegate, new object[] { (Packet)packetsDictionary[1], treeViewPacketInfo }); FillGridViewDelegate fillGridViewDelegate = new FillGridViewDelegate(DataGridViewVisualizer.FillDataGridView); dataGridViewPacketData.Invoke(fillGridViewDelegate, new object[] { (Packet)packetsDictionary[1], dataGridViewPacketData }); } }
private void btnPing_Click(object sender, EventArgs e) { listBoxPing.Items.Clear(); string host = txtBoxPing.Text; if (host == "") { MessageBox.Show("IP地址不能为空"); return; } Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); socket.ReceiveTimeout = 2000; IPHostEntry iphostentry; try { iphostentry = Dns.GetHostEntry(host); } catch (Exception) { listBoxPing.Items.Add("无法识别主机!"); return; } EndPoint hostpoint = (EndPoint) new IPEndPoint(iphostentry.AddressList[0], 0); int DataSize = 4; int PacketSize = DataSize + 8; const int Icmp_type = 8; ICMPPacket packet = new ICMPPacket(Icmp_type, 0, 0, 45, 0, DataSize); Byte[] Buffer = new Byte[PacketSize]; int index = packet.CountByte(Buffer); if (index != PacketSize) { listBoxPing.Items.Add("报文错误!"); return; } 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 i = 0; i < CKsum_buffer_length; i++) { CKsum_buffer[i] = BitConverter.ToUInt16(Buffer, 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) { listBoxPing.Items.Add("报文出错"); return; } int pingNum = 4; listBoxPing.Items.Add("正在ping " + host + " [" + iphostentry.AddressList[0].ToString() + "]"); for (int i = 0; i < 4; i++) { int Nbytes = 0; int startTime = Environment.TickCount; try { Nbytes = socket.SendTo(SendData, PacketSize, SocketFlags.None, hostpoint); } catch (Exception) { listBoxPing.Items.Add("报文传送失败!"); return; } Byte[] ReceiveData = new Byte[256]; Nbytes = 0; int TimeConsume = 0; while (true) { try { Nbytes = socket.ReceiveFrom(ReceiveData, 256, SocketFlags.None, ref hostpoint); } catch (Exception) { listBoxPing.Items.Add("响应超时!"); break; } if (Nbytes > 0) { TimeConsume = System.Environment.TickCount - startTime; if (TimeConsume < 1) { listBoxPing.Items.Add("reply from: " + iphostentry.AddressList[0].ToString() + " Send: " + (PacketSize + 20).ToString() + " time<1ms;bytes Received " + Nbytes.ToString()); } else { listBoxPing.Items.Add("reply from: " + iphostentry.AddressList[0].ToString() + " Send: " + (PacketSize + 20).ToString() + " In " + TimeConsume.ToString() + "ms;bytes Received " + Nbytes.ToString()); } break; } } } socket.Close(); }