Search code examples
python-3.xsocketssystemdtcpserversocketserver

Problem running tcp server via systemd service getting address already in use


I am trying to run SocketServer.TCPServer

Yesterday midnight I put the code for review

https://codereview.stackexchange.com/q/232879/22943,

however I could not get the TCPServer to work with Systemd, now today I have finally pin pointed where the whole problem is in running a TCPServer looking at journalctl logs.

Nov 24 13:33:06 rockpro64 systemd[1393]: Started TCP Server to recieve data from Particle Photon to upload to MySql
Nov 24 13:33:06 rockpro64 python3[1733]: inside main module.
Nov 24 13:33:06 rockpro64 python3[1733]: Traceback (most recent call last):
Nov 24 13:33:06 rockpro64 python3[1733]:   File "/usr/local/iot/home_iot/tcpserver.py", line 92, in <module>
Nov 24 13:33:06 rockpro64 python3[1733]:     main()
Nov 24 13:33:06 rockpro64 python3[1733]:   File "/usr/local/iot/home_iot/tcpserver.py", line 83, in main
Nov 24 13:33:06 rockpro64 python3[1733]:     server = Server(server_address, ParticlePhotonRequestHandler)
Nov 24 13:33:06 rockpro64 python3[1733]:   File "/usr/local/iot/home_iot/tcpserver.py", line 58, in __init__
Nov 24 13:33:06 rockpro64 python3[1733]:     TCPServer.__init__(self, server_address, handler_cls, bind_and_activat
Nov 24 13:33:06 rockpro64 python3[1733]:   File "/usr/lib/python3.6/socketserver.py", line 456, in __init__
Nov 24 13:33:06 rockpro64 python3[1733]:     self.server_bind()
Nov 24 13:33:06 rockpro64 python3[1733]:   File "/usr/lib/python3.6/socketserver.py", line 470, in server_bind
Nov 24 13:33:06 rockpro64 python3[1733]:     self.socket.bind(self.server_address)
Nov 24 13:33:06 rockpro64 python3[1733]: OSError: [Errno 98] Address already in use
Nov 24 13:33:06 rockpro64 systemd[1393]: photon_uploader.service: Main process exited, code=exited, status=1/FAILUR
Nov 24 13:33:06 rockpro64 systemd[1393]: photon_uploader.service: Failed with result 'exit-code'.

From my service unit, I have got rid of socket and made a simplfied version:

[Unit]
Description=TCP Server to recieve data from Particle Photon to upload to MySql.
After=multi-user.target
Wants=network-online.target
After=network-online.target


[Service]
Type=idle
RestartSec=6
EnvironmentFile=/home/rock64/.config/systemd/user/photon_uploader.env
ExecStart=/usr/bin/python3 /usr/local/iot/home_iot/tcpserver.py

[Install]
WantedBy=multi-user.target

still I am getting the same error Address Already in use


Solution

  • Address already in use will mostly occur for 2 reasons:

    1. The address is actually in use by another running process. You can check that by running netstat -pnutl

    2. The address is used by a previous bind attempt made by the same process and didn't have time to close properly. This has a simple solution by turning on the socket option SO_REUSEADDR: s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)