我正在尝试将UDP响应发送到其他IP地址,而该IP地址没有收到初始消息。
当我使用以下代码时,它会失败:
import socket
localIP = "127.0.0.1"
localPort = 6666
bufferSize = 1024
msgFromServer = "Hello UDP Client"
bytesToSend = str.encode(msgFromServer)
# Create a datagram socket
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
# Bind to address and ip
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
# Listen for incoming datagrams
while(True):
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
clientMsg = "Message from Client:{}".format(message)
clientIP = "Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)
new_address = ( '10.124.1.2', 6666 )
# Sending a reply to client
UDPServerSocket.sendto(bytesToSend, new_address)
我遇到以下错误:
UDP server up and listening
Message from Client:[
|x
Client IP Address:('127.0.0.1', 54370)
Traceback (most recent call last):
File "fake.py", line 55, in <module>
UDPServerSocket.sendto(bytesToSend, new_address)
socket.error: [Errno 22] Invalid argument
当我尝试在new_address
中设置新的IP地址时,它失败了。有人可以告诉我如何将消息重定向到不是初始客户端的新IP。谢谢。