Search code examples
pythonnetworkingudpporticmp

How to check if UDP port is open? (python)


I am trying to write a port scanner with python and there is an issue with UDP ports. Google says that I have to send some request and either recieve TimeoutError, meaning server got the message via the port and the port is opened, or recieve ICMP message "Destination unreacheable(Port unreachable)", meaning port is closed. I am able to see ICMP message in Wireshark but have no idea how to make python see it as well.

Now my code for UDP looks like this:

def udp_connection(ip, port, timeout):
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.settimeout(timeout)
        try:
            s.sendto(b'test', (ip, port))
            data, addr = s.recvfrom(1024)
            return "[+] UDP Port Open: " + str(port) + str(data) + '\n'
        except TimeoutError:
            return "[+] UDP Port Open: " + str(port) + 'kinda no response or something' + '\n'
        except:
            return "[+] UDP Port Closed: " + str(port) + '\n'

and this always returns TimeoutError.

Also tried a solution found on stackoverflow to add a raw socket with socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) as s1: and recieve data with data, addr = s1.recvfrom(1024) instead of data, addr = s.recvfrom(1024) but haven't succeeded


Solution

  • Python throws ConnectionResetError exception when trying to receive response from (ip,closedPort) because receiving the ICMP "Destination unreacheable(Port unreachable)" message but the ICMP packet may be blocked by windows firewall, python will not receive it and... that's it. I literally just had to turn it off to make my code work