【发布时间】:2018-05-07 15:14:42
【问题描述】:
所以,我这里有这段代码。这个发件人脚本给我正确的输出。
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 0
MESSAGE = "Hi, can you listen to this?"
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
我尝试在另一台主机上使用此脚本并尝试在两者之间建立通信。 (两个系统都在同一个网络上,例如 00.000.00.xxx ,只有 xxx 部分不同)
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 0
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
while True:
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print "received message:", data
这是输出
Traceback (most recent call last):
File "C:/Users/bshivaku/Desktop/SEnd_Udp_packets.py", line 9, in <module>
sock.bind((UDP_IP, UDP_PORT))
File "C:\Python27\Lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
我在 sender script 上使用了 receiver 的 ip 地址,在 receiver 上使用了 sender ip 地址 我确定我在 UDP_PORT 上犯了一个错误,所以我使用了 PORT= 0 并尝试了。如何请求端口号?如何建立连接?如果不是端口,我哪里出错了?
【问题讨论】:
标签: python networking udp communication packet