我有一个简单的客户端服务器程序和服务器端工作,但由于某种原因我无法让客户端与服务器进行交互。我能够启动服务器并使用nc -u ::1 50007
并连接到它,它按预期工作。
服务器代码:
import socket
import sys
def main():
HOST = '::1'
PORT = 50007
res = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
af, socktype, proto, canonname, sa = res[0]
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.bind(sa)
while True:
data, addr = s.recvfrom(1024)
if not data:
break
print 'server received %r from %r' % (data, addr)
s.sendto(data, addr)
s.close()
except socket.error, msg:
print msg
if __name__ == '__main__':
main()
客户代码:
import socket
import sys
def main():
HOST = '2015:cc00:bb00:aa00::2'
PORT = 50007
res = socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM)
af, socktype, proto, canonname, sa = res[0]
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
s.connect(sa)
s.send('Hello, world')
data, addr = s.recvfrom(1024)
s.close()
print 'Received', repr(data)
except socket.error as e:
print e
if __name__ == '__main__':
main()
我可以从客户端ping服务器,但我也不能nc -u 2015:cc00:bb00:aa00::2 50007
。当我运行客户端代码时,我收到连接拒绝错误。不知道为什么它没有连接,任何想法?
答案 0 :(得分:5)
问题是您的服务器正在侦听localhost ::1
,但您正在尝试连接到2015:cc00:bb00:aa00::2
,这是一个不同的接口。尝试在服务器中设置HOST = "::"
,以使其绑定到所有接口。