I'm trying to check using Python 3.6 if a remote DNS server is listening on port 53 UDP.
This is what I tried:
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
But I get 0 all the time even if the port is close. Trying TCP using SOCK_STREAM works like a charm.
I also tried:
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
But I get 1 all then time even if the port it's open