Reputation: 1
I am trying to develop a test email server that should run in a docker container. The docker container is run with --network=host -P; though for unit tests I would like to use --network=none.
I am deliberately specifying that port 0 should be used (let the OS pick an available port). I then have a function to get the port that was actually used. The server code is
#! /usr/bin/env python3
import asyncio #pylint: disable=unused-import
from aiosmtpd.controller import Controller
class DemoEmailHandler:
async def handle_DATA(self, server, session, envelope):
message = {
'peer' : session.peer,
'mailfrom' : envelope.mail_from,
'to': envelope.rcpt_tos,
'data' : envelope.content}
print(message)
return '250 Message accepted for delivery'
class DemoEmailServer:
def __init__(self):
self._handler = DemoEmailHandler()
self._server = Controller(
handler=self._handler,
hostname="0.0.0.0",
port=0
)
self._server.start()
self._port = self._server.server.sockets[0].getsockname()[1]
def stop(self):
"""Tell the server to stop"""
self._server.stop()
def getPort(self) -> int:
"""Return the port the SMTP (email) server is actually on"""
return self._port
SERVER = DemoEmailServer()
print(SERVER.getPort())
SERVER.stop()
I keep getting connection refused:
Traceback (most recent call last):
File "./demo_email_server.py", line 36, in <module>
SERVER = DemoEmailServer()
File "./demo_email_server.py", line 25, in __init__
self._server.start()
File "/usr/local/lib/python3.8/dist-packages/aiosmtpd-1.4.2-py3.8.egg/aiosmtpd/controller.py", line 223, in start
self._trigger_server()
File "/usr/local/lib/python3.8/dist-packages/aiosmtpd-1.4.2-py3.8.egg/aiosmtpd/controller.py", line 313, in _trigger_server
s = stk.enter_context(create_connection((hostname, self.port), 1.0))
File "/usr/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
If I create a simple server socket using s.bind(('0.0.0.0', 0)) that does not have a connection refused.
(My host and container are both Ubuntu 20.04, python 3.8.5, the container has aiosmtpd 1.4.2 installed from source).
Can anybody help?
Upvotes: 0
Views: 488
Reputation: 38
I think you should select another port that is available on your system. For example try this approach for chosing an available port:
import socket sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("", 0)) host, port = sock.getsockname()
Upvotes: 0