请给我一段python3代码,用于端口扫描。其中有多个进程,发包进程在端口5050只进行发包,收包进程监听端口5050的收包,查看源ip确定哪些ip存活
时间: 2024-03-13 20:45:20 浏览: 138
Python并发:多线程与多进程
以下是一个基于Python 3的多进程端口扫描器,使用了多个进程进行端口扫描和响应处理:
```python
import socket
import struct
import os
import multiprocessing as mp
def send_packet(ip_addr, port):
# 创建套接字对象
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# 构造IP头
source_ip = socket.inet_aton('192.168.1.1')
dest_ip = socket.inet_aton(ip_addr)
ip_header = struct.pack('!BBHHHBBH4s4s', 69, 0, 20 + 8, os.getpid() & 0xFFFF, 0, 255, socket.IPPROTO_ICMP, 0, source_ip, dest_ip)
# 构造ICMP头
icmp_type = 8
icmp_code = 0
icmp_checksum = 0
icmp_identifier = os.getpid() & 0xFFFF
icmp_sequence = 1
icmp_data = b'Hello, World!'
icmp_header = struct.pack('!BBHHH', icmp_type, icmp_code, icmp_checksum, icmp_identifier, icmp_sequence)
# 计算ICMP校验和
icmp_checksum = socket.htons(~(icmp_type + icmp_code + icmp_identifier + icmp_sequence + len(icmp_data)))
icmp_header = struct.pack('!BBHHH', icmp_type, icmp_code, icmp_checksum, icmp_identifier, icmp_sequence)
# 发送数据包
sock.sendto(ip_header + icmp_header + icmp_data, (ip_addr, port))
def receive_packet():
# 创建套接字对象
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
# 监听端口5050
sock.bind(('192.168.1.1', 5050))
# 循环接收ICMP响应包
while True:
packet, addr = sock.recvfrom(1024)
ip_header = packet[0:20]
icmp_header = packet[20:28]
icmp_type, icmp_code, icmp_checksum, icmp_identifier, icmp_sequence = struct.unpack('!BBHHH', icmp_header)
if icmp_type == 0 and icmp_code == 0 and icmp_identifier == os.getpid() & 0xFFFF and icmp_sequence == 1:
print('Host %s is up!' % addr[0])
if __name__ == '__main__':
# 创建进程池
pool = mp.Pool()
# 发送数据包
for i in range(1, 255):
ip_addr = '192.168.1.%d' % i
pool.apply_async(send_packet, (ip_addr, 5050))
# 接收响应包
receive_packet()
```
该程序使用了两个进程,一个进程用于发送数据包到目标主机的端口5050,另一个进程监听端口5050的响应包,并输出存活的主机IP地址。您可以通过修改`send_packet()`函数中的端口参数来扫描不同的端口。需要注意的是,该程序需要以管理员权限运行才能正常工作。
阅读全文