Question
How can I resolve the 'java.net.BindException: Permission denied' error when trying to create a ServerSocket in Java on macOS?
// Sample code to create a ServerSocket in Java
import java.io.IOException;
import java.net.ServerSocket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server is listening on port 8080");
} catch (IOException e) {
e.printStackTrace(); // This may print 'Permission denied' error
}
}
}
Answer
The 'java.net.BindException: Permission denied' occurs when a Java application attempts to bind a ServerSocket to a port that it does not have permission to access. This is common on macOS where system ports are restricted.
// Example of checking current port usage
$ lsof -i :8080
// Example of running with elevated privileges
$ sudo java -cp . Server
Causes
- Attempting to bind to a port below 1024 (privileged ports) without appropriate permissions.
- The port is already in use by another process.
- Firewall or security settings restricting access to the specified port.
Solutions
- Run the application with elevated privileges using 'sudo', if binding to a privileged port (port < 1024) is necessary.
- Use a non-privileged port (ports 1024 and above) for your ServerSocket.
- Check for running processes on the port using commands like 'lsof -i :8080' and terminate them if necessary.
- Adjust Firewall settings to allow access to the port your ServerSocket is trying to bind.
Common Mistakes
Mistake: Attempting to bind to port 80 without using 'sudo'.
Solution: Change the port to 8080 or higher, or run the application as a superuser.
Mistake: Not checking if the port is already in use.
Solution: Use 'lsof' or 'netstat' to check if the desired port is already occupied.
Helpers
- java.net.BindException
- ServerSocket
- macOS
- Permission denied error
- Java ServerSocket issues