Python detects whether the remote UDP port is open

From , 5 Years ago, written in Python, viewed 72 times.
URL https://pastebin.vip/view/7cca4a94
  1. import socket
  2. import threading
  3. import time
  4. import struct
  5. import Queue
  6.  
  7. queue = Queue.Queue()
  8.  
  9. def udp_sender(ip,port):
  10.     try:
  11.         ADDR = (ip,port)
  12.         sock_udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  13.         sock_udp.sendto("abcd...",ADDR)
  14.         sock_udp.close()
  15.     except:
  16.         pass
  17.  
  18. def icmp_receiver(ip,port):
  19.     icmp = socket.getprotobyname("icmp")
  20.     try:
  21.         sock_icmp = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
  22.     except socket.error, (errno, msg):
  23.         if errno == 1:
  24.             # Operation not permitted
  25.             msg = msg + (
  26.                 " - Note that ICMP messages can only be sent from processes"
  27.                 " running as root."
  28.             )
  29.             raise socket.error(msg)
  30.         raise # raise the original error
  31.     sock_icmp.settimeout(3)
  32.     try:
  33.         recPacket,addr = sock_icmp.recvfrom(64)
  34.     except:
  35.         queue.put(True)
  36.         return
  37.     icmpHeader = recPacket[20:28]
  38.     icmpPort = int(recPacket.encode('hex')[100:104],16)
  39.     head_type, code, checksum, packetID, sequence = struct.unpack(
  40.             "bbHHh", icmpHeader
  41.     )
  42.     sock_icmp.close()
  43.     if code == 3 and icmpPort == port and addr[0] == ip:
  44.         queue.put(False)
  45.     return
  46.  
  47. def checker_udp(ip,port):
  48.  
  49.     thread_udp = threading.Thread(target=udp_sender,args=(ip,port))
  50.     thread_icmp = threading.Thread(target=icmp_receiver,args=(ip,port))
  51.  
  52.     thread_udp.daemon= True
  53.     thread_icmp.daemon = True
  54.  
  55.     thread_icmp.start()
  56.     time.sleep(0.1)
  57.     thread_udp.start()
  58.  
  59.     thread_icmp.join()
  60.     thread_udp.join()
  61.     return queue.get(False)
  62.  
  63. if __name__ == '__main__':
  64.     import sys
  65.     print checker_udp(sys.argv[1],int(sys.argv[2]))
  66.  
  67. #//python/8922

Reply to "Python detects whether the remote UDP port is open"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website