[Errno 112] EADDRINUSE

All ESP32 boards running MicroPython.
Target audience: MicroPython users with an ESP32 board.
Post Reply
Didtho
Posts: 6
Joined: Thu Apr 29, 2021 11:03 pm

[Errno 112] EADDRINUSE

Post by Didtho » Thu Apr 29, 2021 11:08 pm

Hello,
I am having a problem with the web server.
Each time the server is restarted, I have the error [Errno 112] EADDRINUSE on the line s.bind (('', 80))
I have to wait about 2 minutes to be able to restart it without problem.
I am in micropython v1.15 with an ESP32.
Can you solve my problem?
Thank you.

marcidy
Posts: 133
Joined: Sat Dec 12, 2020 11:07 pm

Re: [Errno 112] EADDRINUSE

Post by marcidy » Fri Apr 30, 2021 3:27 am

It would be best if you posted the code your running. You probably are not deiniting the server/socket properly. Socket might still be hanging around somewhere.

Didtho
Posts: 6
Joined: Thu Apr 29, 2021 11:03 pm

Re: [Errno 112] EADDRINUSE

Post by Didtho » Fri Apr 30, 2021 8:28 am

This is part of the code that I have lightened. Socket is not used anywhere other than there.
For the output variable, it contains my html page.

Code: Select all

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

while True:
    r, w, err = select.select((s,), (), (), 1)
    if r:
        for readable in r:
            if gc.mem_free() < 102000:
                gc.collect()
            client, client_addr = s.accept()
            client.settimeout(4.0)
            print("Connecté avec le client", client_addr)
            try:
                client_handler(client)
            except OSError as e:
                pass

def client_handler(client_obj):
   try:
	request = client_obj.recv(1024)
        request = str(request)
        client_obj.settimeout(None)
	print('Content = %s' % request)
	
	output = my page html        
        
        response = output        
        client_obj.send('HTTP/1.1 200 OK\n')
        client_obj.send('Content-Type: text/html\n')
        client_obj.send('Connection: close\n\n')
        client_obj.sendall(response)
        client_obj.close()
    except OSError as e:
        client_obj.close()
        print('Connection closed')

marcidy
Posts: 133
Joined: Sat Dec 12, 2020 11:07 pm

Re: [Errno 112] EADDRINUSE

Post by marcidy » Fri Apr 30, 2021 10:13 pm

Try adding:

Code: Select all

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
before bind().

Explained here:
https://stackoverflow.com/questions/322 ... tion-linux

I don't know for sure if that's your problem, but it sounds like it is based on the condition eventually timing out. I haven't confirmed this by digging into it at a lower level to see if this is exactly the case.

Didtho
Posts: 6
Joined: Thu Apr 29, 2021 11:03 pm

Re: [Errno 112] EADDRINUSE

Post by Didtho » Fri Apr 30, 2021 11:30 pm

Thank you so much. It seems to work with the line you made me add.

Post Reply