Fix Python Socket Error 48
Socket Error 48 is a python error which is triggered when the process tries to bind itself to a port that is already in use.
What Causes the “socket.error: [Errno 48] Address already in use” Error?
After brief research, we found the causes to be:
- Process Bound to Port: Whenever a process is created on the server, a port is used by it to communicate with the internet. The port is like a host that can entertain one guest at a time. However, if you don’t specify a port, the server just creates it on the default port. The next time you create a process, a port has to be specified because the default port is already in use.
Solution 1: Specifying Port Number
The error is mostly triggered when a person tries to bound a specific process to the default port and the default port is already bound to a different process. Therefore, in this step, we will be specifying the port on which the process is to be bounded.
- Chances are, you are using the following command to create a process.
$ python -m SimpleHTTPServer
- Instead of this, use this command to create a process.
$ python -m SimpleHTTPServer (Port Number)
- Wait for the process to be created and check to see if the issue persists.
Solution 2: Freeing up the Port
If the port is already in use by a different process, the new process will not be able to function on that port. Therefore, in this step, we will be freeing up the port by terminating the previous process and then running the new one. For that:
- Use the following command to list a number of processes using a specific port.
$ ps -fA | grep python
- The command argument will look something like the following lines.
601 88234 12788 0 9:53PM ttys000 0:00.16 python -m SimpleHTTPServer
- Out of this, the process code that we will use to kill is “88234”.
- Use the following command to kill the process.
kill 88234
Alternatively, you can use the following command to kill it.
sudo kill -9 PID
- You can now bound the process to this port by using the following command.
$ python -m SimpleHTTPServer (Port Number)
- The process will now be created.
Solution 3: Restarting Raspberry Pi (Only For Raspberry Pi)
You can get rid of this error on Raspberry Pi by restarting the Raspberry Pi or by killing the terminal shell. The Raspberry Pi sometimes is unable to kill the processes automatically and triggers this error because of the previous processes already running on the ports.