python socket gives wrong udp port status of remote server

Viewed 41
[user@testserver~]$ sudo nmap -v -Pn -sU -p 152 10.146.25.44

Starting Nmap 5.51 ( http://nmap.org ) at 2022-09-12 16:32 GMT

Initiating UDP Scan at 16:32

Scanning remoteserver.example.com (10.146.25.44) [1 port]

Completed UDP Scan at 16:32, 0.05s elapsed (1 total ports)

Nmap scan report for remoteserver.example.com (10.146.25.44)

Host is up (0.029s latency).

PORT    STATE  SERVICE

152/udp closed bftp

#!/usr/bin/python #(i am running below code as root)

from socket import *

udp_scan=socket(AF_INET,SOCK_DGRAM)

udp_scan.connect_ex(('10.146.25.44',152))

0 ------------------> this is reported open where as nmap shows udp port 152 is closed

I do not have access to remote server. When checked the remote servers port status, socket modules gives wrong result

1 Answers

Connecting a UDP socket just means that the destination address is set on the socket. There is no actual communication with the remote system going on, contrary to TCP. Thus that the connections succeeds does not allow any conclusion about the remote systems being reachable, ports being open or that the remote system even exists.

Instead one actually needs to send data to the system. The first send will succeed since it returns after putting the data in the local socket buffer, i.e. before actually transmitting the data to the system. Once the packet gets transmitted it might reach the target or might lost somewhere in the middle. Only if the target or some middlebox in between actively reacts to the packet, then a conclusion about the peer can be done. Specifically

  • if there is an answer somebody is actively replying to the packet
  • if there is an ICMP unreachable somebody is actively rejecting the packet
  • if no response happens either the packet got lost, got dropped by a firewall or similar or got actually successfully read by the remote server but without responding
Related