So reuseaddr python socket

So reuseaddr python socket

Last updated: Jul 5, 2023
Reading time · 4 min

banner

# Table of Contents

# Python OSError: [Errno 98] Address already in use [Solved]

The article addresses the following 2 related errors:

The Python error «OSError: [Errno 98] Address already in use» occurs when you have another process running on the specified port.

You can resolve the error by using the SO_REUSEADDR attribute or by identifying and stopping the process before you start your server.

If you are on macOS or Linux, you can use the lsof command to get the process ID of the process that is running on the specified port.

Make sure to replace 8000 with your specific port number.

get process running on specified port

If you get a permissions error, rerun the command with sudo .

The PID column contains the ID of the process that is running on the specified port.

You can stop the process by issuing the kill command.

Copied!
sudo kill -9 YOUR_PID>

stop process running on specified port

Make sure to replace the placeholder with the process ID you got from issuing the lsof command.

If you use bash or zsh , you can also try running the following command to stop the python process.

Copied!
# for bash and zsh kill -9 $(ps -A | grep python | awk '$1>')

# Use the SO_REUSEADDR flag before binding the socket

You can also use the socket.SO_REUSEADDR flag before binding the socket to solve the error.

Copied!
import socket sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Make sure to call the sock.setsockopt() method with the socket.SO_REUSEADDR flag before binding the socket.

Copied!
import socket def start_server(): host = socket.gethostname() port = 8000 sock = socket.socket() # 👇️ Call the method before calling bind() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(2) conn, _address = sock.accept() while True: data = conn.recv(1024).decode() if not data: break print("user: " + str(data)) data = input(' > ') conn.send(data.encode()) conn.close() if __name__ == '__main__': start_server()

The socket.setsockopt method sets the value of the given socket option.

The first argument we passed to the method is the message level and the second is the socket.SO_REUSEADDR attribute.

Starting your Python socket server several times with a small delay causes the «OSError: [Errno 98] Address already in use» error.

The cause of the error is that the previous execution has left the socket in a TIME_WAIT state, so it cannot be immediately reused.

You can prevent this behavior by setting the socket.SO_REUSEADDR flag.

Copied!
sock = socket.socket() # 👇️ Call the method before calling bind() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port))

When the socket.SO_REUSEADDR flag is set, the Python kernel reuses local sockets in TIME_WAIT state without waiting for their timeout to expire.

In other words, on POSIX platforms, you can use the socket.SO_REUSEADDR option to reuse the sockets which were previously bound to the same address and are still in a TIME_WAIT state.

It is very important to call the setsockopt() method before you call bind() , otherwise, the method call won’t have an effect.

# Using a different host and port

If the error persists, try to specify a different host and port when calling the bind() method.

Copied!
host = socket.gethostname() port = 5000 sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port))

Assuming the specified port is available, you should be able to connect.

# Set the allow_reuse_address attribute to True

If you got the error when using the SimpleHTTPRequestHandler, set the allow_reuse_address attribute to True .

Copied!
import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: httpd.allow_reuse_address = True print("serving at port", PORT) httpd.serve_forever()

This will enable you to reuse the address, so starting and stopping your server should not cause an «Address already in use» error.

When the allow_reuse_address attribute is set to true , the socket.SO_REUSEADDR flag is set under the hood.

Copied!
# this code runs when `allow_reuse_address` is `True` if self.allow_reuse_address: self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# Setting debug to False in a Flask application

If you got the error in a Flask application, try to set the debug argument to False when calling app.run() .

You can also try to set the use_reloader argument to False if you don’t need to change your code and auto-reload the server.

Copied!
app.run(debug=True, use_reloader=False)

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Читайте также:  Http ddm ufa ru login index php
Оцените статью