gpt4 book ai didi

Python检查udp端口打开

转载 作者:太空狗 更新时间:2023-10-30 02:55:18 25 4
gpt4 key购买 nike

我正在尝试使用 Python 3.6 检查远程 DNS 服务器是否正在监听端口 53 UDP。

这是我尝试过的:

def check_port(host, port):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(1)
try:
result = s.connect_ex((host, port))
except socket.gaierror:
s.close()
return 1
s.close()
return result # 0 == Port is open

但即使端口关闭,我也一直得到 0。尝试使用 SOCK_STREAM 的 TCP 非常有效。

我也试过:

def check_port_udp(host, port):
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(1)
try:
s.sendto('ping'.encode(), (host, port))
s.recvfrom(1024)
except socket.timeout:
s.close()
print(1)
return 1
s.close()
print(0)
return 0 # 0 == Port is open

但是即使端口是打开的,我也一直得到 1

最佳答案

基本思路:向该端口发送一个DNS查询。如果有响应,则该端口是开放的。

import random
import socket
import struct


class SendDNSPkt:
def __init__(self,url,serverIP,port=53):
self.url=url
self.serverIP = serverIP
self.port=port
def sendPkt(self):
pkt=self._build_packet()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1)
sock.sendto(bytes(pkt), (self.serverIP, self.port))
data, addr = sock.recvfrom(1024)
sock.close()
return data

def _build_packet(self):
randint = random.randint(0, 65535)
packet = struct.pack(">H", randint) # Query Ids (Just 1 for now)
packet += struct.pack(">H", 0x0100) # Flags
packet += struct.pack(">H", 1) # Questions
packet += struct.pack(">H", 0) # Answers
packet += struct.pack(">H", 0) # Authorities
packet += struct.pack(">H", 0) # Additional
split_url = self.url.split(".")
for part in split_url:
packet += struct.pack("B", len(part))
for s in part:
packet += struct.pack('c',s.encode())
packet += struct.pack("B", 0) # End of String
packet += struct.pack(">H", 1) # Query Type
packet += struct.pack(">H", 1) # Query Class
return packet

def checkDNSPortOpen():
# replace 8.8.8.8 with your server IP!
s = SendDNSPkt('www.google.com', '8.8.8.8')
portOpen = False
for _ in range(5): # udp is unreliable.Packet loss may occur
try:
s.sendPkt()
portOpen = True
break
except socket.timeout:
pass
if portOpen:
print('port open!')
else:
print('port closed!')

if __name__ == '__main__':
checkDNSPortOpen()

受此启发post

关于Python检查udp端口打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42867192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com