通过套接字发送文件 - bind()

Sending file over socket - bind()

我正在尝试学习如何使用套接字,并将一个 class 放在一起,它接受一个 ip、端口和要发送的文件。它在本地主机上工作,但当我将网络上另一台主机的 ip 传递给它时却不起作用。

这是追溯:

multiprocessing.pool.RemoteTraceback: 
"""
Traceback (most recent call last):
  File "/path/to/anaconda3/envs/env/lib/python3.5/multiprocessing/pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "script.py", line 91, in servr
    servr.bind((self.ip, self.port))
OSError: [Errno 99] Cannot assign requested address
"""

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "script.py", line 163, in <module>
    main()
  File "script.py", line 157, in main
    rmt.client()
  File "script.py", line 85, in client
    machines.update({self.ip: {self.port: path.get()}})
  File "/path/to/anaconda3/envs/env/lib/python3.5/multiprocessing/pool.py", line 608, in get
    raise self._value
OSError: [Errno 99] Cannot assign requested address

这是代码:

class Remote:

    def __init__(self, ip, port, filename):
        self.ip = socket.gethostbyname(ip)
        self.port = int(port)
        self.filename = filename

    def client(self):
        pool = Pool(processes=1)
        path = pool.apply_async(self.servr)
        time.sleep(1)
        client = socket.socket()
        client.connect((self.ip, self.port))
        with open(self.filename, 'rb') as file:
            data = file.read()
            client.sendall(data)
        machines = {}
        try:
            with open("machines.pickle", 'rb') as file:
                machines = pickle.load(file)
        except (EOFError, FileNotFoundError):
            pass
        finally:
            with open("machines.pickle", 'wb') as file:
                machines.update({self.ip: {self.port: path.get()}})
                pickle.dump(machines, file)

    def servr(self):
        servr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        servr.bind((self.ip, self.port))
        servr.listen(5)
        client, addr = servr.accept()
        file = open("." + self.filename, 'wb') if platform.system() == 'Linux' else os.popen(
        "attrib +h " + self.filename, 'wb')
        data = client.recv(6000)
        file.write(data)
        file.close()
        file = "." + self.filename if platform.system() == 'Linux' else self.filename
        os.chmod(file, os.stat(file).st_mode | 0o111)
        client.close()
        servr.close()
        return os.path.abspath(file)

我尝试绑定到 ("", 0),但是代码没有 运行 超过对 accept() 的调用。也许该端口已被使用?我也试过 socket.settimeout(),虽然它从 accept() 中断,程序 运行s 直到第一个方法的字典更新,但没有文件发送。

对于服务器,.bind(('',port))是典型的,意味着在任何接口上接受客户端连接。使用端口 0 不是典型的……使用大于 1024 的数字是典型的。在客户端连接到服务器之前,代码不会 运行 超过 accept,因此在 accept 处停止也是正常的。