pythonsocketssocket.ioudpudpclient

Errno 99 - Cannot assign requested address


I am trying to connect to IP address to receive data. The IP belongs to an AWS ec2 instance and we opened a UDP port on the server. Every time I try to bind, I get this error [Errno 99] Cannot assign requested address

UDP_IP = "XX.XXX.XX.XX"
UDP_PORT = YYY

sock = socket.socket(socket.AF_INET,  # Internet
                     socket.SOCK_DGRAM)  # UDP

sock.bind((UDP_IP, UDP_PORT)) # this is the line throwing the error

# sock.setblocking(0)
while True:
    data, address = sock.recvfrom(4096)
    print("received message:", data)

I have been to goggle around, and some answers suggested that the error message meant that IP should be local, other answers suggested using connect instead of bind which works but I don't receive any messages.


Solution

  • Generally, sock.bind(('',port)) is all you need to receive messages on a port. It means "listen for incoming packets that port on all interfaces" You don't give an idea what 'XX.XXX.XX.XX' refers but you don't have to be specific unless you only want to listen to a specific interface. You don't bind when sending to a port, you just sock.sendto(msg,(serverip,port)). The host receiving the packet also gets the address it was sent from and can .sendto() that address for a reply.

    Here's an example client/server interaction:

    server.py

    import socket
    
    HOST = '' # receive on all interfaces
    PORT = 5000
    
    server = socket.socket(type=socket.SOCK_DGRAM)
    server.bind((HOST,PORT))
    while True:
        data,(ip,port) = server.recvfrom(4096)
        msg = data.decode()
        print(f'from {ip}:{port}> {msg}')
        if msg == 'quit': break # terminate server
        server.sendto(f'Response: <{msg}>'.encode(), (ip,port))
    print('SERVER EXIT')
    

    client.py

    import socket
    
    SERVER = 'localhost' # or specific IP of host accessible by client
    PORT = 5000
    
    client = socket.socket(type=socket.SOCK_DGRAM)
    while True:
        msg = input('Client> ')
        client.sendto(msg.encode(), (SERVER,PORT))
        if not msg or msg == 'quit': break # empty message to quit client only
        response,addr = client.recvfrom(4096)
        print(response.decode())
    print('CLIENT EXIT')
    

    Demo (client):

    C:\> client
    Client> test1
    Response: <test1>
    Client> test2
    Response: <test2>
    Client>                       # empty message only quits client
    CLIENT EXIT
    
    C:\> client                   # 2nd client
    Client> test3
    Response: <test3>
    Client> 你好!
    Response: <你好!>
    Client> quit                  # quit client and server
    CLIENT EXIT
    

    Demo (server):

    C:\> server
    from 127.0.0.1:49164> test1
    from 127.0.0.1:49164> test2
    from 127.0.0.1:49164>
    from 127.0.0.1:49165> test3   # note client port change for 2nd client
    from 127.0.0.1:49165> 你好!
    from 127.0.0.1:49165> quit
    SERVER EXIT