CodexBloom - Programming Q&A Platform

Trouble with UDP socket binding on localhost using Python's asyncio

👀 Views: 53 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
python asyncio sockets udp Python

I'm attempting to set up I'm trying to create a simple UDP server using Python's `asyncio` library, but I'm running into an scenario where the socket doesn't seem to bind properly to localhost... My code looks like this: ```python import asyncio async def handle_client(data, addr): print(f'Received {data} from {addr}') return b'ACK' async def main(): loop = asyncio.get_running_loop() # Create a UDP endpoint print('Creating UDP server...') listen = loop.create_datagram_endpoint(lambda: asyncio.DatagramProtocol(), local_addr=('127.0.0.1', 9999)) transport, protocol = await listen print('Server is listening on port 9999') while True: await asyncio.sleep(1) # Keep the server running try: asyncio.run(main()) except Exception as e: print(f'behavior: {e}') ``` When I run this code, I get an behavior: `OSError: [Errno 98] Address already in use`. I confirmed that nothing else is using port 9999 by running `lsof -i :9999`, and the output shows that the port is free. I also tried changing the port number to 8888, but the same behavior continues. Additionally, I am using Python 3.10 and asyncio version 3.10.0. I checked the firewall settings on my machine to ensure that it allows UDP traffic, but the scenario continues. Could this be related to some configuration in my development environment, or am I missing something in my code? Any help would be appreciated! Any advice would be much appreciated. I'm working in a CentOS environment.