Python检查udp端口打开

Adr*_*sim 5 python udp

我正在尝试使用 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
Run Code Online (Sandbox Code Playgroud)

但即使端口关闭,我也一直得到 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
Run Code Online (Sandbox Code Playgroud)

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

Sat*_*arg 0

以下代码可以帮助您扫描端口 53/udp :

from socket import *
import sys, time
from datetime import datetime

host = ''
ports = [53]

def scan_host(host, port, r_code = 1) : 
    try : 
        s = socket(AF_INET, SOCK_DGRAM)
        code = s.connect_ex((host, port))
        if code == 0 : 
            r_code = code
        s.close()
    except Exception, e : 
        pass
    return r_code

try : 
    host = raw_input("[*] Enter Target Host Address :  ")
except KeyBoardInterrupt : 
    sys.exit(1)

hostip = gethostbyname(host)

for port in ports : 
    try : 
        response = scan_host(host, port)
        if response == 0 : 
            print("[*] Port %d: Open" % (port))
    except Exception, e : 
        pass
Run Code Online (Sandbox Code Playgroud)

您可以参考此示例进一步探索端口扫描。