The Socket.Error: [Errno 98] Address Already In Use error in Python typically occurs when a socket is trying to bind to an address that is already in use by another socket. This can happen if a previous instance of your program did not close properly, or if another program is using the same port.
Here are some steps to resolve this issue:
Check for Running Processes: Ensure that no other process is using the same port. You can use tools like lsof or netstat to check which processes are using which ports.
lsof -i :netstat -tuln | grep
If you find a process using the port, you can terminate it or use a different port for your application.
Set the SO_REUSEADDR Socket Option: This option allows the socket to bind to an address that is in a TIME_WAIT state, which can help avoid the Address Already In Use error.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)s.bind((host, port))
Properly Close Sockets: Ensure your program properly closes sockets when it terminates. Use try-finally blocks to guarantee that sockets are closed.
import socket
try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(5) # Your socket operations herefinally: s.close()
Wait for the Socket to be Released: If the port is in use due to a previous process that has not yet fully terminated, waiting a few seconds can sometimes resolve the issue.
Restart Your System: If you are unable to identify and terminate the process using the port, restarting your system can free up the port.
Here is an example of using SO_REUSEADDR in a complete socket program:
import sockethost = '127.0.0.1'port = 12345s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)try: s.bind((host, port)) s.listen(5) print(f"Server listening on {host}:{port}") while True: conn, addr = s.accept() print(f"Connected by {addr}") # Handle the connection conn.close()finally: s.close()
By following these steps, you should be able to resolve the Address Already In Use error and run your socket program successfully.