Python Socket [Errno 10049] 'The requested address is not valid in its context'

匿名 (未验证) 提交于 2019-12-03 01:46:01

问题:

I'm trying to get a python socket code to work. The server is running fine, but the client won't bind to an IP address. Here's the error:

Traceback (most recent call last):   File "chatClient.py", line 27, in <module>     s.bind((host, port))   File "C:\Panda3D-1.8.1\python\lib\socket.py", line 224, in meth     return getattr(self._sock,name)(*args) socket.error: [Errno 10049] The requested address is not valid in its context Press any key to continue . . . 

And here's the code...

import socket import threading import os import time  tLock = threading.Lock() shutdown = False  def receving(name, sock):     while not shutdown:         try:             tLock.acquire()             while True:                 data, addr = sock.recvfrom(1024)                 print str(data)         except:             pass         finally:             tLock.release()  host = '76.106.199.228' port = 0  server = ('76.106.199.228', 5000)  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind((host, port)) s.setblocking(0)  rT = threading.Thread(target=receving, args=("RecvThread",s)) rT.start()  alias = raw_input("Name: ") message = raw_input(alias + ": ") while message != 'q':     if message != '':             s.sendto(alias + ": " + message, server)     tLock.acquire()     message = raw_input(alias + ": ")     tLock.release()     time.sleep(0.2)  shudown = True rT.join() s.close() 

What's wrong with the code? I've been searching around google, this website, and a few others, but can't seem to find anything. When I try the solutions they just don't work... Thanks for helping.

回答1:

host needs to be a local address

 bind(...) method of socket._socketobject instance     bind(address)      Bind the socket to a local address.  For IP sockets, the address is a     pair (host, port); the host must refer to the local host. For raw packet     sockets the address is a tuple (ifname, proto [,pkttype [,hatype]]) 

Is it possible you mean s.connect instead?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!