Errno 99 - 无法分配请求的地址

Errno 99 - Cannot assign requested address

我正在尝试连接到 IP 地址以接收数据。 IP 属于 AWS ec2 实例,我们在服务器上打开了一个 UDP 端口。 每次尝试绑定时,我都会收到此错误 [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)

我一直在四处张望,一些答案表明错误消息意味着 IP 应该是本地的,其他答案建议使用 connect 而不是 bind 这有效但我没有收到任何消息。

通常,sock.bind(('',port)) 是您在端口上接收消息所需的全部。它的意思是“监听所有接口上的传入数据包”你不知道 'XX.XXX.XX.XX' 指的是什么,但你不必具体,除非你只想监听一个特定的接口。发送到端口时不绑定,你只是 sock.sendto(msg,(serverip,port))。接收数据包的主机也会得到发送它的地址,并且可以 .sendto() 该地址进行回复。

这是一个示例 client/server 互动:

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')

演示(客户端):

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

演示(服务器):

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