Created
May 4, 2021 12:01
-
-
Save jollyreal/8123859952b5cb9d4b72931ddb2b8b6d to your computer and use it in GitHub Desktop.
An UDP server that listen to 100 ports and give response when those ports received any UDP packet.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import socket | |
import select | |
if __name__ == "__main__": | |
# constant of program | |
IP_ADDRESS = "192.168.11.10" | |
PORT_NO_START = 10024 | |
PORT_NO_END = 10124 | |
# the payload that UDP server will response | |
PAYLOAD_STRING = f"I got your message\r\n" | |
payload_ascii = PAYLOAD_STRING.encode("utf-8").hex() | |
payload = bytes.fromhex(payload_ascii) | |
# sockets that listen to ports 10024 until 10123, total of 100 ports | |
udp_sockets = [] | |
for port in range(PORT_NO_START,PORT_NO_END): | |
server_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) | |
server_socket.bind((IP_ADDRESS,port)) | |
udp_sockets.append(server_socket) | |
# infinity loop to response to the incoming udp packet | |
while True: | |
readable, writable, exceptional = select.select(udp_sockets,[],[]) | |
for socket in readable: | |
(client_data,(client_ip,client_port)) = socket.recvfrom(1024) | |
# send out the response back to the request | |
socket.sendto(payload,(client_ip,client_port)) | |
print(f"sent to {client_ip}:{client_port}") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment