Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
use the concurrent module to execute the UDP request
import socket
import select
import time
from concurrent import futures
def udp_request(src_ip,src_port,dst_ip,dst_port):
'''send an UDP packet that contain a string of "hello" to the dst_ip:dst_port from src_ip:src_port'''
# create the request socket
request_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
# prepare the payload
payload_string = "hello\r\n"
payload_ascii = payload_string.encode("utf-8").hex()
payload = bytes.fromhex(payload_ascii)
# send out the UDP packet
# use select to set timeout of 1 sec
# if there is a response from the server, return the payload from server
# if nothing response after 1 sec, return "no response"
ready =[request_socket],[],[],1)
if ready[0]:
(server_data,(server_ip,server_port)) = request_socket.recvfrom(1024)
response = f"{server_ip}:{server_port} -> {src_ip}:{src_port} == {server_data.decode().strip()}"
response = f"no response from {dst_ip}"
return response
def concurrent_request(src_ips,src_ports,dst_ips,dst_ports,max_worker=20):
'''use the concurrent method to execute the udp_request function'''
# decide the number of maximum workers
workers = min(max_worker,len(dst_ports))
with futures.ThreadPoolExecutor(workers) as executor:
res =,src_ips,src_ports,dst_ips,dst_ports)
answer = []
for item in res:
return answer
if __name__ == "__main__":
# constant of the program
SRC_IP = ""
SRC_PORT_END = 12124
DST_IP = ""
DST_PORT_END = 10124
src_ip_list = [SRC_IP for _ in range(SRC_PORT_END - SRC_PORT_START)]
src_port_list = [i for i in range(SRC_PORT_START,SRC_PORT_END)]
dst_ip_list = [DST_IP for _ in range(DST_PORT_END-DST_PORT_START)]
dst_port_list = [i for i in range(DST_PORT_START,DST_PORT_END)]
# use the for loop method to send 100 times udp request print out the time taken of execution
time_before = time.time()
for _src_port,_dst_port in zip(src_port_list,dst_port_list):
response = udp_request(SRC_IP,_src_port,DST_IP,_dst_port)
# print(response)
time_after = time.time()
print(f"one by one: {time_after-time_before} sec")
# use the concurrent method to send 100 times udp request print out the time taken of execution
time_before = time.time()
time_after = time.time()
print(f"concurrent: {time_after-time_before} sec")
print("program end")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment