Python UDP网络socket.error:[Errno 10049]

时间:2017-05-06 21:47:03

标签: python-2.7 networking udp

我正在尝试使用Python代码建立一个简单的UDP连接,通过互联网在2台PC之间建立。 代码在PC_1上运行:

import socket
import time

HOST = "ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
    s.sendto(data, (HOST, PORT))
    print "sent: ",data
    time.sleep(1)

代码在第二台PC上运行:

import socket

HOST = "ip_address_of_PC1"
PORT = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.bind((HOST,PORT))

while True:
    print s.recv(30)

在第二台PC上运行代码时出现以下错误消息:

return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context

2 个答案:

答案 0 :(得分:0)

print s.recv(30)更改为:

data, addr = s.recvfrom(30)
print data

在第二个PC代码中,HOST变量需要第二个PC ip的值,而不是第一个:

HOST = "ip_address_of_PC2"

答案 1 :(得分:0)

在PC1上运行代码:

import socket
import time

HOST = "public ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:
    s.sendto(data, (HOST, PORT))
    print "sent: ",data
    time.sleep(1)

在PC2上运行代码:

import socket

HOST = "private ip_address_of_PC2"
PORT = 5555

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.bind((HOST,PORT))

while True:
    print s.recv(30)