Python OSError: [Errno 98] Address already in use but no port is used

13.8k Views Asked by At

I have problem with my code using flask(http, as main thread), ngrok and tcp server (both ngrok and tcp server is running on two threads) at the same time (see below for error message)

Traceback (most recent call last):
  File "/home/monki/anaconda3/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/home/monki/anaconda3/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/monki/VSCode/Python/Webhook/app.py", line 49, in launchServer
    s.bind((hostname, TCP_PORT))
OSError: [Errno 98] Address already in use

I have checked the port using

ps -fA | grep python

and found no port is being used

root         910       1  0 15:02 ?        00:00:00 /usr/bin/python3 /usr/bin/networkd-dispatcher --run-startup-triggers
root        1036       1  0 15:02 ?        00:00:00 /usr/bin/python3 /usr/share/unattended-upgrades/unattended-upgrade-shutdown --wait-for-signal
x       6316    5499  0 15:55 pts/0    00:00:00 grep --color=auto python

This is my code

from flask import Flask, request, Response
import json
import socket
import threading  
from pyngrok import ngrok

from queue import Queue

#tcp server
TCP_IP = ''
TCP_PORT = 13370
BUFFER_SIZE  = 20

# http server
HOST_URL = 'http://xxx.ngrok.io'


def start_ngrok():
    ### sorry i have to blank out the account
    ngrok.set_auth_token("xxxxxx")
    url = ngrok.connect(5000, subdomain='xxx').public_url
    print(' * Tunnel URL:', url)


def launchServer(out_q):
    print("TCP thread started")
    hostname = socket.gethostname()
    local_ip = socket.gethostbyname(hostname)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    s.bind((hostname, TCP_PORT))
    s.listen(1)

    while True:
        print('waiting for a connection')
        conn, addr = s.accept()
        try:
            print(sys.stderr + 'client connected:' + addr)
            while True:
                out_q.put(data)
                data = conn.recv(1024)

                # print >>sys.stderr, 'received "%s"' % data
                if data:
                    conn.sendall(data)
                else:
                    break
        finally:
            conn.close()

app = Flask(__name__)

# route definition
@app.route('/<webhookAddr>', methods=['POST'])
def response(in_q, webhookAddr):

    if webhookAddr == 'getGithub':
        # data = json.loads(request.data)
        print(request.json)

        in_q.put(request.json)
        return Response(status=200)
    
    elif webhookAddr == 'getGitHub2':
        print(request.json)
        return Response(status=200)
    else:
        return Response(status=200)


if __name__ == '__main__':
   q = Queue()

   t1 = threading.Thread(target=launchServer, args =(q, ))
   t1.daemon = True
   t1.start()

   t2 = threading.Thread(target=start_ngrok)
   t2.daemon = False
   t2.start()

   app.run(debug=True)

However, by running the code portion of launchServer alone, I do not get such error. So did i use ngrok wrongly. Need your help to point out my error

Regards

2

There are 2 best solutions below

0
On BEST ANSWER

This problem recreates on my side too. From debugging the Flask code, it looks like in debug mode there's no usage of SO_REUSEADDR, so the next attempt to bind with the same address (your tcp server) would fail. One option is to turn off the debug mode:

app.run(debug=False)

Another option is to turn off the reloader (the reloader is good if you're modifying your application while the server is running):

app.run(debug=True, use_reloader=False)
2
On

Maybe your port 5000 is already occupied by some other process. Try netstat

netstat -anp  | grep 5000