With the proliferation of massive varieties and unknown malicious viruses, it is difficult to achieve effective and timely defence by anti‐virus technology with virus signature matching as the core. Hence, the research of malicious code detection and defence is investigated. Firstly, it introduces the defence technology and detection technology. The simulation results show that the default infection probability of the simulation program is 15.1%. The default detection probability is 60.1%, the default number of nodes is 1000, the default time step is 1000 ms, and the default initial infected node is only node 0, that is, only the malicious code on node 0 is activated. After start‐up, the whole P2P starts to run, and the number of infected nodes increases. Finally, all nodes are infected. The infection speed becomes faster and faster. When the number of infected nodes reaches about half, the infection speed begins to slow down.