How Python detects whether a remote UDP port is open _python

Source: Internet
Author: User

This example describes how Python detects whether a remote UDP port is open. Share to everyone for your reference. The implementation methods are as follows:

Copy Code code as follows:
Import socket
Import threading
Import time
Import struct
Import Queue
Queue = Queue.queue ()
def udp_sender (Ip,port):
Try
ADDR = (ip,port)
SOCK_UDP = Socket.socket (socket.af_inet,socket. SOCK_DGRAM)
Sock_udp.sendto ("ABCD ...", ADDR)
Sock_udp.close ()
Except
Pass
def icmp_receiver (Ip,port):
ICMP = Socket.getprotobyname ("ICMP")
Try
sock_icmp = Socket.socket (socket.af_inet, socket. Sock_raw, ICMP)
Except Socket.error, (errno, msg):
If errno = 1:
# Operation not permitted
msg = msg + (
"-Note this ICMP messages can only is sent from processes"
"Running as root."
)
Raise Socket.error (MSG)
Raise # Raise the original error
Sock_icmp.settimeout (3)
Try
RECPACKET,ADDR = Sock_icmp.recvfrom (64)
Except
Queue.put (True)
Return
Icmpheader = recpacket[20:28]
icmpport = Int (recpacket.encode (' hex ') [100:104],16)
Head_type, code, checksum, Packetid, sequence = Struct.unpack (
"Bbhhh", Icmpheader
)
Sock_icmp.close ()
if code = = 3 and Icmpport = = port and addr[0] = = IP:
Queue.put (False)
Return
def checker_udp (Ip,port):
THREAD_UDP = Threading. Thread (target=udp_sender,args= (Ip,port))
THREAD_ICMP = Threading. Thread (target=icmp_receiver,args= (Ip,port))
thread_udp.daemon= True
Thread_icmp.daemon = True
Thread_icmp.start ()
Time.sleep (0.1)
Thread_udp.start ()

Thread_icmp.join ()
Thread_udp.join ()
Return Queue.get (False)
if __name__ = = ' __main__ ':
Import Sys
Print checker_udp (Sys.argv[1],int (sys.argv[2))

I hope this article will help you with your Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.