使用Socket实现简单的端口扫描功能。分别 针对TCP和UDP,采用多线程技术实现端口扫描,给出扫描 结果
时间: 2024-05-03 22:18:48 浏览: 214
以下是使用Socket实现TCP和UDP端口扫描的Python代码:
```python
import socket
import threading
# TCP端口扫描
def tcp_scan(ip, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((ip, port))
if result == 0:
print("[+] TCP Port {} open".format(port))
sock.close()
except:
pass
# UDP端口扫描
def udp_scan(ip, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1)
data = b"Hello, this is a test message"
sock.sendto(data, (ip, port))
recv_data, addr = sock.recvfrom(1024)
if recv_data:
print("[+] UDP Port {} open".format(port))
sock.close()
except:
pass
if __name__ == '__main__':
ip = input("IP Address: ")
threads = []
for port in range(1, 1001):
t_tcp = threading.Thread(target=tcp_scan, args=(ip, port))
threads.append(t_tcp)
t_udp = threading.Thread(target=udp_scan, args=(ip, port))
threads.append(t_udp)
for t in threads:
t.start()
for t in threads:
t.join()
```
代码中使用了多线程技术,分别对TCP和UDP进行扫描。运行程序后输入目标主机的IP地址,程序会扫描目标主机的1-1000号端口,并输出开放的TCP和UDP端口。
示例输出:
```
IP Address: 127.0.0.1
[+] TCP Port 135 open
[+] TCP Port 139 open
[+] TCP Port 445 open
[+] TCP Port 5357 open
[+] UDP Port 137 open
[+] UDP Port 138 open
```
在示例中,我输入了本地主机的IP地址,程序扫描出本地主机开放了TCP的135、139、445和5357端口,以及UDP的137和138端口。
阅读全文